Bash Quirks: understanding behavior of set -e

There is one bash quirk I just learnt today and that caused me fair amount of debugging. In summary when you use the set -e option in bash, any function that returns a non-zero exit code will cause your script to terminate except that this does not apply when the function is inside an if statement – more accurately when the function forms the argument of an if clause. We can see this behavior in action below:

#!/bin/bash
set -e

function func {
  if [ "$1" = "$2" ] ; then
    return 0
  else
    return 1
  fi
}

VAR1=foo
VAR2=bar

if func $VAR1 $VAR2 ; then
   echo "func returned 0"
else
   echo "func returned 1. set -e does not cause script to exit."
fi

SOME_VAR=$(func $VAR1 $VAR1)

echo "SOME_VAR = $SOME_VAR. the function returns 0 so execution continues till here."

SOME_OTHER_VAR=$(func $VAR1 $VAR2)

echo "we never get here and program exits beforehand since function returns 1 and set -e causes script to exit."

Here is output of running this script:

$ ./test.sh
func returned 1
SOME_VAR = . the function returns 0 so execution continues till here.

$ echo $?
1
This entry was posted in Software and tagged . Bookmark the permalink.

Leave a comment