Search code examples
bashshell

What is the proper way to detect shell exit code when errexit option is set?


I prefer to write solid shell code, so the errexit & nounset is always set.

The following code will stop after bad_command.

#!/bin/bash
set -o errexit
set -o nounset
bad_command # stop here
good_command

I want to capture it, here is my method:

#!/bin/bash
set -o errexit
set -o nounset
rc=1
bad_command && rc=0 # stop here
[ $rc -ne 0 ] && do_err_handling
good_command

Is there any better or cleaner method?

My Answer:

#!/bin/bash
set -o errexit
set -o nounset
if ! bad_command ; then
  # error handling here
fi
good_command

Solution

  • How about this? If you want the actual exit code ...

    #!/bin/sh                                                                       
    set -e
    
    cat /tmp/doesnotexist && rc=$? || rc=$?                                         
    echo exitcode: $rc        
    
    cat /dev/null && rc=$? || rc=$?                                                 
    echo exitcode: $rc   
    

    Output:

    cat: /tmp/doesnotexist: No such file or directory
    exitcode: 1
    exitcode: 0