我们知道传递给shell脚本的参数是以空格分开的,如果参数中有空格该怎么处理呢?
在Java程序中可以调用shell脚本来完成一些与Linux系统相关度较高的工作,其调用方式主要可以有以下两种:
1.
Process process = null;
Runtime runTime = Runtime.getRuntime();
process = runTime.exec("sh test.sh aa bb");
process.waitFor();
其中test.sh为脚本名称,aa和bb为test.sh的两个参数,中间以逗号隔开。最后调用waitFor()方法等待脚本执行完毕。
2.
Process process = null;
Runtime runTime = Runtime.getRuntime();
String[] commands = new String[]{"test.sh","aa","aa bb"};
process = runTime.exec(commands);
process.waitFor();
其中test.sh为脚本名称,aa和"aa bb"为test.sh的两个参数,可以看到第二个参数中有空格,这种方法可以很好的处理传递shell脚本中参数有空格的问题。