I would like to execute 2 or more commands sequentially through my Java Application using ProcessBuilder class. I Have tried multiple options as suggested in other responses/forums but no luck.
Here are the things I have tried:
ProcessBuilder processBuilder = new ProcessBuilder("ls", ";", "pwd");
Gives me following error :
Errors : ls: ;: No such file or directory Errors : ls: pwd: No such file or directory
ProcessBuilder processBuilder = new ProcessBuilder("ls", "&&", "pwd");
Gives me similar error:
Errors : ls: &&: No such file or directory Errors : ls: pwd: No such file or directory
List<String> command = new ArrayList<String>();
command.add("ls");
command.add(";");
command.add("pwd");
ProcessBuilder processBuilder = new ProcessBuilder(command);
Gives me following error:
Errors : ls: ;: No such file or directory Errors : ls: pwd: No such file or directory
My OS is Linux/Mac-OSX.
The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds.
Running Multiple Commands as a Single Job We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.
Your approaches are equivalent to calling ls
with the specified arguments. In Bash notation, what you're running is:
ls ';' pwd
ls '&&' pwd
If you want ls
and pwd
to be run as separate commands, you can use Bash (or another shell language) to wrap them into a single command:
bash -c 'ls ; pwd'
which you can call this way:
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "ls ; pwd");
I'm using ProcessBuilder to compile java program like this and it works for me:
ProcessBuilder b = new ProcessBuilder("cmd.exe","/c","cd " + dir,
" & javac " + mapClassName + ".java -cp " + pathToProjectClasses);
So I have 2 commands, first one is cd
command and second one is javac
command and i execute them sequentially using &
.
Sorry for my bad writing skills, if I haven't explained my code well please ask me about anything you want to know.
You could get the Process from ProcessBuilder.start() from the first command, wait using waitFor() and then launch the second one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With