ProcessBuilder executes one command from the String list but doesn't executes the next one.

StackOverflow https://stackoverflow.com/questions/20407055

  •  29-08-2022
  •  | 
  •  

Question

I am a newbie in programming. I created a String list for ProcessBuilder. ProcessBuilder is executing one command from the String list (and successfully writes a file I asked to write) but doesn't execute the next String command. Here is the code:

List<String> vsArrays = new ArrayList<String>();
vsArrays.add("/bin/sh");
vsArrays.add("-c");
vsArrays.add("echo '123' > ~/1.rad");
vsArrays.add("echo '123' > ~/2.rad");
vsArrays.add("echo '123' > ~/3.rad");

for (String s : vsArrays){
 system.out.println(s);
}

ProcessBuilder proc = new ProcessBuilder(vsArrays);
Process start = proc.start();
start.waitFor();

The first file (named 1.rad) is created in the home (~) directory but the following files are not. Although I managed to execute the next commands (and write the other files) by using redirectInput from a file, but I dont want to create a separate file for redirectInput. Can you please answer why the next commands (from the string list) are not getting executed? Thanks!

Was it helpful?

Solution

ProcessBuilder was never meant to execute multiple commands. The entries of the List are treated as arguments and it is the invoked program sh which executes the one argument due to the -c option. So it’s the sh command and it’s -c option which “decide” to interpret one argument, and only one, as a command to start. But the bash will run multiple commands being provided as a single argument separated by ;.

List<String> vsArrays = new ArrayList<String>();
vsArrays.add("/bin/sh");
vsArrays.add("-c");
vsArrays.add("echo '123' > ~/1.rad; echo '123' > ~/2.rad; echo '123' > ~/3.rad");

ProcessBuilder proc = new ProcessBuilder(vsArrays);
Process start = proc.start();
start.waitFor();

OTHER TIPS

I haven't used process builder for a while, but I believe you are passing the 4 last strings as arguments to the first string (the executable). In which case, I'm not sure the command you have constructed i valid syntax. Try something like (haven't tested the code myself but should give you some ideas):

private void myMainFunction() {
  doWrite("1.rad");
  doWrite("2.rad");
  doWrite("3.rad");
}

private void doWrite(String filename) {
  List<String> vsArrays = new ArrayList<String>();
  vsArrays.add("/bin/sh");
  vsArrays.add("-c");
  vsArrays.add("echo '123' > ~/" + filename);

  for (String s : vsArrays){
    system.out.println(s);
  }

  ProcessBuilder proc = new ProcessBuilder(vsArrays);
  Process start = proc.start();
  start.waitFor();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top