我在linux下编写了一个shell脚本moveDirectory.sh,代码为:
if [ -d ${moveDirectory}/${batchDate} ]; then
mv -f ${batchNumDir}/* ${moveDirectory}/${batchDate}/
echo "aa"
else
echo "bb"
mv -f ${batchNumDir} ${moveDirectory}
fi
这段代码在linux终端下可以正常执行,但是我在java程序中通过调用执行该shell脚本,则发生错误,调用的代码为:
Process proc = Runtime.getRuntime().exec("moveDirectory.sh");
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// 记录输出流
while ((line = br.readLine()) != null) {
logger.debug(line);
}
// 等待进程结束
proc.waitFor();
// 进程非正常结束打印错误信息
if (proc.exitValue() != 0) {
br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while ((line = br.readLine()) != null) {
logger.error(line);
}
}
显示的错误信息为[ERROR-10:37:21]ShellTask.shell脚本执行失败(140) - shell脚本执行失败
java.io.IOException: Cannot run program "if": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:466)
at com.huateng.topafs.frame.ShellTask.execCmds(ShellTask.java:120)
at com.huateng.topafs.frame.ShellTask.execProcess(ShellTask.java:103)
at com.huateng.topafs.frame.ShellTask.run(ShellTask.java:79)
at com.huateng.topafs.frame.BatchRunner.runTask(BatchRunner.java:201)
at com.huateng.topafs.frame.BatchRunner.run(BatchRunner.java:55)
at com.huateng.topafs.frame.BatchRunner.main(BatchRunner.java:257)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.(UNIXProcess.java:148)
at java.lang.ProcessImpl.start(ProcessImpl.java:65)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 8 more:
经在网上查询相关错误信息,得到的结论是java可以调用linux的外部程序指令,如cp、mv等,但是调用不到linux的系统指令,如cd、if、passwd等。
我在linux终端上面用which指令查询cp和cd指令所在的路径,显示结果为:
[devafs:/home/devafs/batch/sbin] which cp
/bin/cp
[devafs:/home/devafs/batch/sbin] which cd
/usr/bin/which: no cd in (/usr/java/jdk1.6.0_14/bin:/usr/java/jdk1.6.0_14/jre/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/home/devafs/bin:/oracle/product/11.1.0/db_1/bin:/home/devafs/bin:/home/afsadm/sqllib/bin:/home/afsadm/sqllib/adm:/home/afsadm/sqllib/misc:/home/afsadm/sqllib/lib:/home/afsadm/sqllib/bin:/home/devafs/apache-ant-1.7.1/bin:/home/devafs/apache-maven-2.2.1/bin:.)
由于我刚刚接触linux系统,目前无法解决该问题,只能将错误定位到这里,所以请朋友们能够指点迷津,我将不胜感谢!