1

I have tried running a shell script from a Java program, but the entire script is not being executed. And idea why we might come across such problem?

The Java code to execute shell script:

File file = new File("/path/to/script");
String COMMAND= "./run";
ProcessBuilder p = new ProcessBuilder(COMMAND);
p.directory(file);
try {
    Process startProcess= p.start();
} catch (IOException e) {
    e.printStackTrace();
}

The script runs fine but not whole script is executed. It seems like only the 1st line is being executed.

3
  • What's the first line of the script? Are you sure only the first line runs? Commented Oct 30, 2011 at 13:52
  • See also this possible duplicate: Failure to start program from java (using ProcessBuilder) Commented Oct 30, 2011 at 13:54
  • Whenever I hear of this problem, and see code like above, it reminds me to recommend reading and implementing all the tips of When Runtime.exec() won't. Consuming (and reporting, in some fashion) the System.out/err of the Process might for instance, be illuminating (or indeed, the root of the problem). Commented Oct 30, 2011 at 14:32

1 Answer 1

1

If you are sure that the script starts running the problem is not in java but in script itself.

The reason of difference may be the wrong path or wrong environments. When you are running script from console you are in your user's environment, so script can use all environment variables.

Try to add some debug outputs to figure the problem out.

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

3 Comments

Hi, The script runs fine when I run it via terminal in ubuntu. But the same script is not totally executed from the java program. The script has some tinyos commands. I also had the same problem when I tried to run script with tinyos commands with 'make'. Thanks.
It's almost certain that your PATH is set one way in your terminal settings, and differently in you java environment. As AlexR says, add some debugging messages to your script OR add full path prefixes to all commands that you are executing in the script. Good luck.
Hi, there is no problem in path, I guess, the problem is environment variable. The part of script which is not being executed is: if cygpath -w / >/dev/null 2>/dev/null; then CLASSPATH="oscilloscope.jar;$CLASSPATH" else CLASSPATH="oscilloscope.jar:$CLASSPATH" fi java Oscilloscope Furthermore, echo ... inside the script doesn't give any output when the script is executed from java program. I can see the output when i run the script from Terminal. Ashish.

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.