This is because the echo
command is not resolving the $$
but bash
is.
As Java does not run the command in the bash
shell, this does not work.
If you run the command in bash
then it will work, but it won't return what you might expect; it will return information about bash
rather than the Java process:
/bin/bash -c 'echo $$' -> pid of bash process
/bin/bash -c 'echo $?' -> bash exit code
/bin/bash -c 'echo $0' -> /bin/bash
This is because you are now running another command ('/bin/bash') and the information given is about that command rather than your JVM.
In short, there is no easy way to do the things you want in Java.
Here's a quick test case to prove this (code significantly tidied and using Guava):
public static void main(final String[] args) throws Exception {
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
runCommand("/bin/bash", "-c", "echo $$");
runCommand("/bin/bash", "-c", "echo $?");
runCommand("/bin/bash", "-c", "echo $0");
}
private static void runCommand(String... command) throws IOException {
ProcessBuilder pb = new ProcessBuilder(command);
Process prs = pb.start();
try (InputStream is = prs.getInputStream()) {
byte[] b = ByteStreams.toByteArray(is);
System.out.println(new String(b, StandardCharsets.UTF_8));
}
}
Output:
4466@krypto.local
4467
0
/bin/bash
So you can see that the pid is one higher than the JVM pid. And the program name is '/bin/bash'.