Pirate Cheat Sheets
Shell scripts that don’t break

Bash scripting
cheat sheet

Bash scripting at a glance: strict mode, variables and quoting, parameter expansion, arrays, tests, loops, functions, redirection, traps, getopts and the new 5.3 features.

Version
v5.3.20
Commands
150
Sections
14

Version notes · Bash scripting 5.3.20

  • 5.3 adds ${ cmd; }: command substitution in the current shell, no subshell fork. ${| cmd; } returns $REPLY.
  • 5.3 adds GLOBSORT (sort globs by name, size, mtime…), source -p PATH, read -E and BASH_TRAPSIG.
  • macOS ships bash 3.2 at /bin/bash: no associative arrays, mapfile or ${var,,}. Install a newer one (brew install bash).
  • Use #!/usr/bin/env bash so the first bash on PATH runs the script.

Bash is the default shell on most Linux systems and the usual choice for glue scripts: run commands, move files, check results, and stop loudly when something fails.

Pairs withShellCheckshfmtcoreutilsgrepsedawkjq

Strict mode

set -euo pipefail

Quote everything

"$var", "$@", "${arr[@]}"

Lint it

shellcheck catches the traps

When to stop

>100 lines? consider Python

Quick start

cat > hello.sh <<'EOF'#!/usr/bin/env bashset -euo pipefailname="${1:-world}"echo "Hello, ${name}!"EOFchmod +x hello.sh && ./hello.sh Ada
  • Shebang: first bash on PATH
  • Exit when a command fails
  • Error on unset variables
  • A pipe fails if any part fails
  • All three ("strict mode")
  • Split words on newline / tab only
  • Run from the script’s folder
  • Call main last, pass all arguments
  • Make it executable

script.sh

#!/usr/bin/env bashset -euo pipefailusage() {  echo "usage: ${0##*/} [-v] FILE" >&2  exit 2}main() {  local verbose=0  while getopts "vh" opt; do    case $opt in      v) verbose=1 ;;      *) usage ;;    esac  done  shift $((OPTIND - 1))  [[ $# -eq 1 ]] || usage  (( verbose )) && echo "file: $1"  wc -l < "$1"}main "$@"

set -e is skipped inside if, while, && / || chains and functions called from them. Check important commands explicitly.

  • Assign (no spaces around =)
  • Always double-quote expansions
  • Braces to separate from text
  • Single quotes: no expansion
  • ANSI-C quoting for escapes
  • Constant
  • Pass to child processes
  • Function-local variable
  • Integer: n+=1 does math
  • Set a variable for one command
  • Remove a variable

Defaults & checks

  • Default if unset or empty
  • Default, and assign it
  • Exit with an error if unset / empty
  • Value only if var is set
  • Length
  • Indirect: value of the var named in name

Trim, replace, case

  • Basename (strip longest */ prefix)
  • Dirname (strip shortest /* suffix)
  • Drop the extension
  • Just the extension
  • Replace first (// = all)
  • Substring: offset 0, length 3
  • Uppercase (,, lower, ^ first char)

Indexed

  • Create
  • Append
  • One element (-1 = last)
  • All elements, each quoted
  • Count
  • Slice
  • File lines into an array
  • Split a string

Associative (maps)

  • Create
  • Set a key
  • Get a key
  • All keys
  • Key exists?
  • Delete a key
  • Iterate

Strings & numbers

  • Empty (-n = not empty)
  • Equal (quote the right side for a literal)
  • Glob match
  • Regex; groups in BASH_REMATCH
  • Numeric comparison
  • Numeric inside [[ (-eq -ne -le -gt -ge)

Files

  • Regular file exists
  • Directory exists
  • Anything exists
  • Exists and not empty
  • Executable (-r readable, -w writable)
  • Newer than

Branching

  • if / elif / else
  • Short-circuit
  • Require a tool
  • Pattern match on a value
  • Over files (glob)
  • Over arguments
  • Range ({0..100..5} with a step)
  • C-style
  • Read a file line by line
  • Split fields
  • Safe for any file name
  • Retry until it works
  • No match → no iterations (not a literal *.log)
  • Leave the loop / next iteration

Functions

  • Define
  • Call (no parentheses)
  • Capture its output
  • Exit status (0–255), not a value
  • Error helper
  • Print a function

Arguments

  • Positional arguments
  • All arguments, each quoted
  • Number of arguments
  • Drop $1, move the rest down
  • Script name
  • Short options (o: takes a value)
  • Stdout to a file (overwrite)
  • Append
  • Stderr to a file
  • Stdout + stderr (or &> all.log)
  • Discard errors
  • Print to stderr
  • Stdin from a file
  • Show and save
  • Pipe stdout + stderr
  • Process substitution: output as a file
  • Here-string
  • Here-doc (<<'EOF' = no expansion, <<- strips tabs)
  • Log the rest of the script
  • Output of a command
  • Nested pipes are fine
  • Same, without a subshell (5.3+)
  • Value of REPLY from the block (5.3+)
  • Integer math: 3
  • Increment in place
  • Compound assignment
  • Power: 1024
  • Decimals need bc or awk
  • Format into a variable: 00042
  • Exit status of the last command
  • Allow a failure under set -e
  • Branch on failure
  • Status of every part of the last pipe
  • Private temp dir
  • Clean up however the script ends
  • Report where it failed
  • Handle Ctrl-C / kill (5.3 var)
  • Exit with a status (0 = success)
  • Kill a command after 10 s (coreutils)
  • Prompt for input
  • Hidden input
  • Timeout after 5 s
  • One key press
  • Formatted output
  • Shell-quoted (safe to reuse)
  • Is stdout a terminal?
  • Numbered menu
  • Run in the background
  • PID of the last background job
  • Wait for it, get its exit status
  • Wait for all jobs
  • Wait for the next one to finish
  • Stop it (TERM)
  • 4 in parallel
  • Keep running after logout
  • Command substitution without a subshell (5.3)
  • Sort glob results newest first (name, size, atime…) (5.3)
  • Look up a sourced file on a custom path (5.3)
  • Read with readline + bash completion (5.3)
  • Monotonic clock, for timing (5.3)
  • Unix time with microseconds (5.0)
  • 32-bit random number (5.1)
  • & in ${s/x/&&} = the match (5.2, on by default)
  • Syntax check, don’t run
  • Print each command as it runs
  • Trace one part
  • Show file:line in traces
  • Lint: quoting, pitfalls, portability
  • Format
  • What cmd resolves to (alias, function, file)