I am running a java program from within a Bash script. If the java program throws an unchecked exception, I want to stop the bash script rather than the script continuing execution of the next command.
How to do this? My script looks something like the following:
#!/bin/bash
javac *.java
java -ea HelloWorld > HelloWorld.txt
mv HelloWorld.txt ./HelloWorldDir
From stackoverflow
-
Catch the exception and then call System.exit. Check the return code in the shell script.
-
#!/bin/bash function failure() { echo "$@" >&2 exit 1 } javac *.java || failure "Failed to compile" java -ea HelloWorld > HelloWorld.txt || failure "Failed to run" mv HelloWorld.txt ./HelloWorldDir || failure "Failed to move"Also you have to ensure that
javaexits with a non-zero exit code, but that's quite likely for a uncaught exception.Basically exit the shell script if the command fails.
-
In agreement with Tom Hawtin,
To check the exit code of the Java program, within the Bash script:
#!/bin/bash javac *.java java -ea HelloWorld > HelloWorld.txt exitValue=$? if [ $exitValue != 0 ] then exit $exitValue fi mv HelloWorld.txt ./HelloWorldDir
0 comments:
Post a Comment