Running .sh files with Java's exec in a different directory?

我的梦境 提交于 2019-12-13 02:29:10

问题


I'm writing a Java program MyAwesomeProgram that uses Process' exec function to run bash commands locally. My code is located in /home/a/b/c, and there are .sh files located in /home/a/b/d that I need to run. However, when I run my code:

Process p;
Runtime rt = new Runtime.getRuntime();
p = rt.exec("./home/a/b/d/shell.sh");
p.waitFor();

I receive an error:

Exception in thread "main" java.io.IOException: Cannot run program "./home/a/b/d/shell.sh": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:431)
at java.lang.Runtime.exec(Runtime.java:328)
at MyAwesomeProgram.main(MyAwesomeProgram.java:186)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
at java.lang.ProcessImpl.start(ProcessImpl.java:65)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)

I believe this is just a mistake in formatting the exec command String, however I haven't been able to find a solution thus far. Where have I messed up? Any other tips/tricks for using exec effectively would be appreciated, but completely optional. Thanks!

Edit: I got the code working, it was an issue with a couple directory references I got backwards as well as what Woot4Moo said.


回答1:


well if your program lives in:

/home/a/b/c

and your scripts live in:

/home/a/b/d

and you use the . you are not in the right directory. You want to exec it with the following path:

../d/script.sh

The . says use the current directory + your string. So in essence your input is the following:

/home/a/b/c/home/a/b/d

The .. allows you to go up one directory which if you are at :

/home/a/b/c

you want then arrive at:

/home/a/b


来源:https://stackoverflow.com/questions/10093985/running-sh-files-with-javas-exec-in-a-different-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!