shBash
IntermediateLesson 10 of 15

Exit Codes, Error Handling & set -euo pipefail – Bash

Reliable scripts: detect errors, abort and clean up.

Every command returns an exit code: 0 = success, 1–255 = error. You read the one from the last command with $?. && runs the next command only on success, || only on failure. With exit N you end a script yourself.

ls /tmp > /dev/null
echo "Exit-Code: $?"            # 0
ls /gibt-es-nicht 2> /dev/null
echo "Exit-Code: $?"            # 2 (with GNU ls; macOS: 1 – only 0 vs. non-zero counts)

mkdir backup && echo "created" || echo "failed"
grep -q ERROR server.log && echo "Error found in the log"
cd /gibt-es-nicht || { echo "Folder missing" >&2; exit 1; }

By default Bash simply carries on after errors – dangerous if something is deleted afterwards, for example. The "strict mode" at the start of a script catches many cases:

  • set -e – the script aborts as soon as a command fails (exceptions: commands in if conditions, before &&/||, negation with !).
  • set -u – accessing unset variables is an error (catches typos like $DIR_).
  • set -o pipefail – a failure anywhere in a pipeline counts as a failure of the pipeline (otherwise only the exit code of the last command counts).
  • Combined: set -euo pipefail, often with IFS=$'\n\t' for safe word splitting.
#!/usr/bin/env bash
set -euo pipefail

quelle="${1:?Please provide a source folder}"     # abort with a message if $1 is missing
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT                  # ALWAYS cleans up: on success, error, Ctrl+C

cp -r "$quelle"/. "$tmp"/                  # if this fails, the script aborts
echo "Copied to $tmp"
grep -q "X" "$tmp"/notiz.txt || echo "no X found – that's fine, because of ||"
Warningset -e is tricky: in if cmd; then or cmd || true a failure does not trigger an abort, and local x=$(command) swallows the exit code of command. Write local x; x=$(command) on two lines. If grep finds no matches, it returns exit code 1 – under set -e and pipefail in a pipeline this is often unwanted.
TipError messages belong on stderr (echo "..." >&2) so that users' pipes and redirects are not distorted. Choose meaningful exit codes and document them.