To execute a UNIX shell script, first the shell needs to be executed. This can be done using an object of java runtime class.
Writing the name of the shell script on the shell's stdin stream will execute the script, provided it is in the search path. The code example given below executes a shell script named MyShellScript:
To get the return code from the shell script call:
In this case:
One thing to note is that, the script executes concurrently in a separate process and not a thread within JVM.
To wait for the process to finish, call Process.waitFor(). In this case:
rtime = Runtime.getRuntime();
Process child = rtime.exec(“/bin/bash”);
Writing the name of the shell script on the shell's stdin stream will execute the script, provided it is in the search path. The code example given below executes a shell script named MyShellScript:
BufferedWriter outCommand = new BufferedWriter(new
OutputStreamWriter(child.getOutputStream()));
outCommand.writeLine(“MyShellScript”);
outCommand.flush();
To get the return code from the shell script call:
Process.exitValue() function.
In this case:
int retCode = child.exitValue();
One thing to note is that, the script executes concurrently in a separate process and not a thread within JVM.
To wait for the process to finish, call Process.waitFor(). In this case:
child.waitFor();