alpha

Bash

Quick reference for Bash scripting patterns

#bash#shell#scripting

Using #!/usr/bin/env bash Shebang

#!/usr/bin/env bash

Better than #!/bin/bash because:

  • env searches $PATH for bash, finds it anywhere
  • Portable across Linux, macOS, and BSD

Using set Options for Safer Bash Scripts

#!/usr/bin/env bash
set -euxo pipefail
  • -e - exit immediately on error
  • -u - treat unset variables as error
  • -x - print commands before execution
  • -o pipefail - fail pipeline if any command fails, not just the last

Without pipefail:

curl http://example.com | grep "pattern"  # exits 0 even if curl fails

Using trap for Cleanup in Bash Scripts

Run cleanup on script exit, error, or interrupt:

#!/usr/bin/env bash
set -euxo pipefail

cleanup() {
    rm -rf "$TMPDIR"
}
trap cleanup EXIT

TMPDIR=$(mktemp -d)
# script continues...

Common signals:

  • EXIT - always runs on exit (success or failure)
  • ERR - runs on error (with set -e)
  • INT - runs on Ctrl+C
  • TERM - runs on kill

Only one handler per signal. New trap replaces previous one - combine logic in single function.

Getting Script Directory in Bash

Get absolute path of directory containing the script:

WORKDIR=$(cd -- "$(dirname -- "$0")" && pwd -P)
export WORKDIR

Useful for referencing files relative to script location, regardless of where script is called from.

References