BASH Exit Codes

I’ve been learning a lot about BASH lately and am working on re-writing my Base32 Decoder and HMAC scripts before releasing the full OTP script.

One of the topics that helps with signalling and control flow between BASH functions is exit codes. Understanding the results of calling exit and the exit code that is stored in $?.

#!/bin/bash

function myFunction {
   echo $1
   exit $1
}

# Call 1
var=$(myFunction 1)
echo "Exit 1: $?"

# Call 2
(myFunction 2)
echo "Exit 2: $?"

# Call 3
(( var += 1 ))
echo "Exit 3: $?"

# Call 4
(( 1 / 0 ))
echo "Exit 4: $?"

# Call 5
myFunction 5
echo 'The last line.'

Call 1 captures the stdout of myFunction in var, captures the exit code, then prints the exit code of myFunction,.

Call 2 prints directly to stdout, captures the exit code, and prints the exit code of myFunction.

Call 3, the exit code of the arithmetic operation is printed.

Call 4, shows that a failed arithmetic operation returns a non-zero exit code. Note: Most operations will succeed, even if invalid parameters are given.

Call 5 shows that when a directly called function (i.e. not in a subshell) exits, it causes the whole script or function to exit (i.e. the last line is never executed).

Running the script produces the following output:

Exit 1: 1
2
Exit 2: 2
Exit 3: 0
./test.sh: line 21: ((: 1 / 0 : division by 0 (error token is " ")
Exit 4: 1
5