views:

1617

answers:

3

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
+6  A: 

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

Tom Hawtin - tackline
+1  A: 
#!/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.

Douglas Leeder
+1  A: 

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