3

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.

1
  • The original post didn't have a newline between #!/bin/bash and echo "Hello World". Erci says the script worked from the command line, so I'm assuming that was just a formatting issue, and added the newline. Commented Jul 2, 2011 at 14:54

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Process proc = runtime.exec(cmd, new String[0], new File("/home/ercan/Desktop"));
@erci: yes? Is there something about that line that isn't working?
The line with process proc.... Gives error " No suggation avaible" . İ think i need new Java code
@ercidi I think it's Runtime.getRuntime()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.