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();
本文介绍如何使用Java运行Unix Shell脚本。通过创建Java Runtime对象执行/bin/bash,并通过标准输入流传递脚本名称来调用指定的Shell脚本。此外,还介绍了如何获取Shell脚本的返回值及等待脚本执行完成。

5

被折叠的 条评论
为什么被折叠?



