>_ IzzyLab

Hands-on task

This task is step 8 of the course “Clean scripts: shellcheck”

Turn on strict mode

medium~7 min

The script /root/deploy.sh keeps going even after a command fails and ends up reporting "success", although the copy failed. Make it fail-fast: the script must exit immediately with a non-zero code

  • at the first command that fails;
  • when it references a variable that has no value assigned (instead of a silent empty string);
  • when any command inside a pipeline fails, not just the last one.

Turn this behavior on with shell options at the top of the script — don't rewrite the script's commands. In the end, running /root/deploy.sh must not create /root/status.txt.

What you'll practise:
  • shellcheck
  • set -euo pipefail
  • strict mode
  • exit codes
  • fail-fast

Topic breakdown

Bash "strict mode" is three options at the top of a script. set -e aborts execution at the first command with a non-zero exit code (without it the script carries on, piling up errors). set -u turns a reference to an undeclared variable into an error instead of a silent empty string. set -o pipefail makes a pipeline return the exit code of the failed stage, not just the last one. Together (set -euo pipefail) they give predictable fail-fast behavior, which is critical for deploy scripts.

What's checked

  1. all three safeguards are on in the script: failed commands, unset variables, pipelines
  2. the script stops on an error

What it looks like