6

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

3 Answers 3

13

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
Sign up to request clarification or add additional context in comments.

Comments

10

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

Comments

3
#!/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 java exits with a non-zero exit code, but that's quite likely for a uncaught exception.

Basically exit the shell script if the command fails.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.