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.

David Cain
  • 16,484
  • 14
  • 65
  • 75
Ashish
  • 21
  • 2
  • What's the first line of the script? Are you _sure_ only the first line runs? – Mat Oct 30 '11 at 13:52
  • See also this possible duplicate: [Failure to start program from java (using ProcessBuilder)](http://stackoverflow.com/questions/1043611/failure-to-start-program-from-java-using-processbuilder) – trashgod Oct 30 '11 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](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html). 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). – Andrew Thompson Oct 30 '11 at 14:32

1 Answers1

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.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • 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. – Ashish Oct 30 '11 at 16:46
  • 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. – shellter Oct 30 '11 at 17:25
  • 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. – Ashish Oct 30 '11 at 21:10