DEV Community

Circuit Times
Circuit Times

Posted on Fully Autonomous

A strict-mode Bash script template, explained line by line

Most Bash scripts start as five lines and grow until one silent failure costs an afternoon. This is a starter file for new scripts. It fails early, cleans up after itself and tells you which line broke.

The whole file is on GitHub: circuittimes/bash-script-template.

The first three lines

#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
Enter fullscreen mode Exit fullscreen mode
  • env bash finds Bash through PATH, so the script also runs on systems where Bash is not in /bin.
  • -e stops on a failed command. -u stops on an unset variable. -o pipefail makes a pipeline fail when any stage fails, not only the last one.
  • -E lets the ERR trap fire inside functions too.
  • The IFS line stops word splitting on spaces, which protects file names that contain them.

Clean up on every exit

cleanup() {
  local status=$?
  if [[ -n "$WORKDIR" && -d "$WORKDIR" ]]; then
    rm -rf -- "$WORKDIR"
  fi
  exit "$status"
}
trap cleanup EXIT
Enter fullscreen mode Exit fullscreen mode

The EXIT trap runs whether the script succeeds, fails or calls exit itself. Saving $? first keeps the original exit status, so a failed run still reports failure after the cleanup.

Say where it broke

on_error() {
  log "error: command failed on line $1"
}
trap 'on_error "$LINENO"' ERR
Enter fullscreen mode Exit fullscreen mode

With set -e alone, a script just stops. This trap prints the line number first.

Keep messages off standard output

log() {
  printf '%s [%s] %s\n' "$(date +%H:%M:%S)" "$SCRIPT_NAME" "$*" >&2
}
Enter fullscreen mode Exit fullscreen mode

Logs go to standard error. Standard output stays clean, so the script can sit in a pipeline.

What we checked

We ran the template with GNU Bash 5.2.21 on Linux: the success path, a missing argument, an unreadable file and -h. ShellCheck 0.11.0 reports no warnings. We did not run it on the Bash 3.2 that ships with macOS.

A real run looks like this:

12:36:49 [template.sh] debug: working directory is /tmp/tmp.nNapLgQDWW
12:36:49 [template.sh] notes.txt has 3 lines
Enter fullscreen mode Exit fullscreen mode

Going further

Strict mode has edge cases, such as commands that are allowed to fail and local hiding an exit status. Our full guide covers those with examples: Bash scripting tutorial and best practices.

If you spot a problem in the template, open an issue on the repository.

Disclosure: Circuit Times used Claude, an AI model made by Anthropic, to help prepare this post. Circuit Times is responsible for the checks and the conclusions.

Top comments (0)