Is "bash" required to run exec commands from Java?

53 views Asked by At

The logged output shows the command which is run, as can be seen this includes a bash command:

thufir@dur:~/NetBeansProjects/threadedExecTelnet$ 
thufir@dur:~/NetBeansProjects/threadedExecTelnet$ gradle run                                                       

> Task :run                                                                                                        
May 19, 2020 12:25:47 P.M. net.bounceme.dur.exec.ExecList execute
INFO: [bash, -c, ls /home/thufir/NetBeansProjects/threadedExecTelnet]
build
build.gradle
gradle
gradlew
gradlew.bat
LICENSE
README.md
settings.gradle
src

BUILD SUCCESSFUL in 859ms
3 actionable tasks: 1 executed, 2 up-to-date
thufir@dur:~/NetBeansProjects/threadedExecTelnet$                          

While I don't overly mind the laborious and verbose code:

public void execute() throws IOException {
    log.info(listToExec.toString());

    String[] arrayToExec = listToExec.toArray(new String[0]);
    Process process = Runtime.getRuntime().exec(arrayToExec);

    InputStream inputStream = process.getInputStream();
    Reader inputStreamReader = new InputStreamReader(inputStream);
    try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
            System.out.flush();
        }
    }
}

I don't understand why, sometimes, it seems like bash is required, othertimes not.

1

There are 1 answers

0
DuncG On

For commands built into the shell then first argument needs to be the shell. But if the command to run is a normal executable then using that directly with qualified path should work. For "ls" you can check:

which ls

That would probably print /bin/ls or similar, and so you could try launch from Java without bash as:

listToExec = new String[] {"/bin/ls", "/home/thufir/NetBeansProjects/threadedExecTelnet"}

Note that some people may have shell alias for "ls" so the there could be different behaviour of /bin/ls directly versus "ls" from within your normal bash session or via java calling "bash -c ls blah"