how.wtf

Catch and handle errors in Bash

· Thomas Taylor

Bash does not natively support a try/catch syntax for errors; however, there are options for handling errors within a script.

Try and Catch errors in Bash

For the first technique, simply detect if there’s a non-zero status by using the following syntax:

1if ! command_call; then
2    echo "command_call did not complete successfully"
3fi

In addition, an || (or) expression may be used instead:

1command_call || echo "command_call did not complete successfully"

For explicitness, the full syntax for a try/catch in Bash is:

1if command_call ; then # try
2    echo "tried and was successful"
3else # catch
4    echo "command_call did not complete successfully"
5fi

If command_call is not successful, the echo statement will be invoked in all scenarios.

Error handling in Bash

For the second technique, bash provides a native variable for reporting exit codes: $?. Some users may want to catch and handle specific exit codes.

1command_call
2
3status=$?
4if [ $status -eq 1 ]; then
5    echo "General exception"
6elif [ $status -eq 127 ]; then
7    echo "The command could not be found!"
8fi

#Bash  

Reply to this post by email ↪