开发者

How can I call a shell script from a Java program?

I use ubuntu 10.04 with eclipse. I created a shell script, exam.sh:

#!/bin/bash 
echo "Hello World"

with chmod 755 exam.sh

On the command line, I can execute ./exam.sh // ok command showing me Hello World

I want to call this exam.sh with java code, this is my java code:

public static void main(String[] args) {    
Runtime r = Runtime.getRuntime();
Process p = null;
String cmd[] = {"/bin/bash","cd","/home/erdi/Desktop", ".","/","exam.sh"};

try {
    p = r.exec(cmd);
    System.out.println("testing...");//开发者_StackOverflow中文版ok
} catch (Exception e) {
    e.printStackTrace();
}
}

This doesn't function, where did I make a mistake? Yes I know i can search by google but I didn't find an answer to my problem. It gives howTos and tutorials about this feature but I didn't find an answer.


Try this instead:

cmd[] = {"/bin/bash", "/home/ercan/Desktop/exam.sh"};

You can just invoke bash on the shell script directly. To run a command string (like cd) you would need to use the -c switch.

If you need the working directory of the script to be your Desktop, you can use another overload of Runtime.exec:

Process proc = Runtime.getRuntime().exec(cmd, new String[0], new File("/home/ercan/Desktop"));

Alternatively, the ProcessBuilder class makes executing processes a bit nicer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜