Stop bash script if Java exception is thrown

I am running a java program from a Bash script. If the java program throws an exception, I want to stop the Bash script, and not the script, from continuing with the next command.

How to do it? My script looks something like this:

#!/bin/bash javac *.java java -ea HelloWorld > HelloWorld.txt mv HelloWorld.txt ./HelloWorldDir 
+4
source share
3 answers

Catch the exception and then call System.exit. Check the return code in the shell script.

+10
source

According to Tom Hawtin

To check the exit code of a Java program, in a Bash script:

 #!/bin/bash javac *.java java -ea HelloWorld > HelloWorld.txt exitValue=$? if [ $exitValue != 0 ] then exit $exitValue fi mv HelloWorld.txt ./HelloWorldDir 
+11
source
 #!/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" 

You should also make sure java exits with a non-zero exit code, but this is likely for an uncaught exception.

Basically exit the shell script if the command does not work.

+3
source

All Articles