Exit statuses and debugging

Tracing scripts with set -x, reading $? at the right moment, and making scripts stop at the first error.

What you'll learn
  • Trace a script's execution with set -x
  • Check a command's exit status correctly
  • Use set -euo pipefail to make failures loud

Tracing

debug_bash_script_1.sh turns on tracing with set -x. Every command is then printed — after expansion, prefixed with + — on standard error before it runs:

+ echo 'Hello Prajol'
Hello Prajol
+ ls

Seeing the expanded command is the fastest way to find quoting bugs: an empty variable or an unexpected split is visible at once. Trace a whole script without editing it with bash -x script.sh, and switch tracing off again with set +x.

$? describes the last command — only the last

debug_bash_script_2.sh checks for an error like this:

echo "HEllo"
x=12
echo "Value of variable x is: $x"

if [ $? -ne 0 ]; then
    echo "Error ocurred"
fi

$? holds the exit status of the most recent command, which here is the second echo. It is 0 whatever happened earlier, so the check can never fire. To test a command, test it directly — if was built for exactly this:

if ! cp source.txt backup/; then
    echo "copy failed" >&2
    exit 1
fi

or save $? in a variable immediately after the command, before anything else overwrites it.

Failing loudly

By default a Bash script carries on after a failing command, often doing damage with half-finished results. Three options change that, and many scripts start with all of them:

set -euo pipefail
  • -e exits as soon as a command fails (with some deliberate exceptions, such as commands tested by if).
  • -u treats an unset variable as an error — unbound variable — instead of silently expanding it to nothing, which catches typos in variable names.
  • -o pipefail makes a pipeline fail if any part fails. Without it, false | true has status 0, because only the last command counts; with it, the status is 1.

Try it yourself. Fix debug_bash_script_2.sh so that its check tests a command that can actually fail, such as ls "$dir". Then add set -euo pipefail to the top of the if/else script from lesson 2 and run it with an empty answer. Which line stops it, and why?

View source on GitHub →