0

I am using below command to execute a shell script from java. I also need to check if script execution is successful without any errors. Is there any possible method to do this? Please advise.

ProcessBuilder pb = new ProcessBuilder("test.sh", arg1, arg2);
Process p = pb.start();
Karthik
  • 145
  • 3
  • 15
  • Thank you :) somehow it did not come up in the suggestions while typing question. Let me try that – Karthik May 03 '16 at 15:33

2 Answers2

1

You need to check if the process terminated which you can do with Process.waitFor() which blocks until the process completed. The return value of this call is the return code of the system command you invoked.

Bernhard
  • 8,583
  • 4
  • 41
  • 42
1

To handle asynchronously, attach a threaded listener to Process.getErrorStream (ie listen to the read() method). When the process closes, you will get an IOException, releasing the thread. Then call Process.exitValue(). If you got anything coming off of the error stream or Process.exitValue() is not == 0, then that hints to probable failure

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80