ThomasKelly ThomasKelly - 2 months ago 6
Bash Question

Using Java's getRuntime.exec() to Run a Linux Shell Command: How?

Below is a python script that executes a linux bash command "echo Hello World > ./output"

import os

os.system("bash -c \"echo Hello World > ./output\"");


I am trying to do the same with Java. Below is my best effort, following the instructions I found here: Want to invoke a linux shell command from Java

import java.io.IOException;

public class callCommand {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec(
new String[]{"bash","-c",
"\"echo Hello World > ./output\""});
} catch(IOException e) {
e.printStackTrace();
}
}
}


It compiles without issue, and runs without complaint, but no output file is generated.

Answer

The extra quotes around echo ... should be removed:

Process p = Runtime.getRuntime().exec(new String[]{
        "bash", "-c",
        "echo Hello World > ./output"
});

The python version needs extra quotes to tell the underlying system that echo Hello World > ./output is a single argument. The java version explicitly specifies arguments as separate strings, so it doesn't need those quotes.

Also, your version doesn't "run without complaint", you just don't see the complaints, because you don't read the error stream of the created process.