typestar

set -euo pipefail in Bash

The safety prelude, and cleanup that always runs.

# the safety prelude for real scripts
set -euo pipefail
# -e: exit on error   -u: unset vars are errors   pipefail: pipes too

missing=${UNSET_DEMO:-fallback}
echo "under -u, defaults still work: $missing"

# trap runs cleanup on the way out, however the script leaves
cleanup() { echo "cleanup ran"; }
trap cleanup EXIT

false || echo "a guarded failure does not kill the script"
echo "reached the end"

How it works

  1. -e exits on errors, -u on unset variables, pipefail on pipes.
  2. :- defaults still work under -u.
  3. trap ... EXIT runs cleanup however the script leaves.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
403
Tokens
35
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 25 seconds.

Type this snippet

Step 1 of 3 in Scripts & safety, step 22 of 26 in Language basics.

← Previous Next →