I’ve been using python for a long time. python’s system and subprocess methods can take shell=True attibute to spawn an intermediate process setting up env vars. before the command runs. I’ve be using Java back and forth and using Runtime.exec() to execute shell command.
Runtime rt = Runtime.getRuntime(); Process process; String line; try { process = rt.exec(command); process.waitFor(); int exitStatus = process.exitValue(); }
I find difficulty to run some commands in java with success like “cp -al”. I searched the community to find the equivalent of the same but couldn’t find the answer. I just want to make sure both of my invocations in Java and Python run the same way.
Advertisement
Answer
Two possible ways:
-
String[] command = {"sh", "cp", "-al"}; Process shellP = Runtime.getRuntime().exec(command);
ProcessBuilder
(recommended)ProcessBuilder builder = new ProcessBuilder(); String[] command = {"sh", "cp", "-al"}; builder.command(command); Process shellP = builder.start();
As Stephen points on the comment, in order to execute constructs by passing the entire command as a single String, syntax to set the command
array should be:
String[] command = {"sh", "-c", the_command_line};
If the -c option is present, then commands are read from string.
Examples:
String[] command = {"sh", "-c", "ping -f stackoverflow.com"}; String[] command = {"sh", "-c", "cp -al"};
And the always useful*
String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};
*may not be useful