How to run Unix shell script from Java code?
To run a Unix shell script from Java code, you can use the Runtime.getRuntime().exec()
method to execute the script.
Here is an example of how to do this:
String scriptPath = "/path/to/script.sh";
Process process = Runtime.getRuntime().exec(scriptPath);
process.waitFor();
int exitValue = process.exitValue();
if (exitValue == 0) {
System.out.println("Script executed successfully");
} else {
System.out.println("Script failed with exit value: " + exitValue);
}
In this example, the exec()
method is used to execute the script.sh
script, and the waitFor()
method is used to wait for the script to finish executing. The exitValue()
method is then used to get the exit value of the script, which indicates whether the script completed successfully or encountered an error.
You may also need to set the executable flag on the script file using the chmod
command before you can execute it from Java.
I hope this helps. Let me know if you have any questions.