I'm trying to run some commands from a Java application using Runtime.getRuntime().exec(command)
. However, certain commands that work from a command line tool like Terminal fail when executed like this.
Example:
private static final String COMMAND = "cp -n /home/me/Downloads/a.png /home/me/Downloads/b.png";
private static final String COMMAND_2 = "cp -n /home/me/Downloads/a.png /home/me/Downloads/b.png && cp -n /home/me/Downloads/a.png /home/me/Downloads/b.png";
public static void main(String[] args) throws Exception {
int result = Runtime.getRuntime().exec(COMMAND).waitFor();
System.out.println(result); // prints 0
int result2 = Runtime.getRuntime().exec(COMMAND_2).waitFor();
System.out.println(result2); // prints 1
}
Note that COMMAND_2
does the same as COMMAND
twice, separated by &&
. Why does one succeed, but the other fail? Both work just fine in Terminal.
I'm using Oracle-Java 1.7.0 on Red Hat Enterprise Linux 6.
cp
, e.g./bin/cp
.ProcessBuilder
; 2. aProcess
is not a shell interpreter!bash
with my command as argument.bash
is an example of a shell interpreter; andbash
is itself a process. But there is no reason to usebash
at all for a process, except if you execute a shell script.