Java执行Shell脚本“No such file or directory”异常的可能原因

来源:互联网 发布:时时彩助赢软件下载 编辑:程序博客网 时间:2024/05/21 02:51

用Runtime.getRuntime().exec()方法执行Linux的一个Shell脚本时,报

Cannot run program "./script/abc.sh": java.io.IOException: error=2, No such file or directory]
java.io.IOException: Cannot run program "./script/abc.sh": java.io.IOException: error=2, No such file or directory

 

原因一:

最终发现是这个shell脚本本身有问题,字符是windows格式(主要是换行符导致),用 vi 打开这个shell脚本就可以看到每一行后面有 ^M 的字符,把这个文件转到 Linux 格式就可以了,方法如下:

 

解决方法:

[root@localhost script]# dos2unix -o abc.sh 
dos2unix: converting file abc.sh to UNIX format ...

 

原因二:

shell 脚本所带参数中含有JAVA中不可解释的字符,如“*”;误转移字符“$”,“-”

 

解决方法:

在之行命令前面叫上“sh -c”

[root@localhost script]# sh -c "abc.shtest

原创粉丝点击