简体   繁体   中英

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...");//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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM