options
set (options)
Changes shell option flags and/or replaces positional parameters. The 'safer bash' idiom 'set -euo pipefail' is the most common use — it turns on error-exit, unset-variable-error, and pipeline failure propagation.
set [-abefhkmnptuvxBCEHPT] [-o OPTION] [--] [ARG ...] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| -e / -o errexit | Exit immediately if any command returns non-zero |
| -u / -o nounset | Error on referencing an unset variable |
| -o pipefail | Pipeline status = last non-zero, not just the last command |
| -x / -o xtrace | Print each command before executing (debug) |
| -E / -o errtrace | Make ERR traps inherit into functions/subshells |
| +X | Disable option X (opposite of -X) |
| set -- ARGS | Replace positional parameters with ARGS |
Examples
set -euo pipefail The canonical strict-mode preamble for bash scripts.
set -x; cmd; set +x Trace a single block for debugging.
set -- one two three; echo "$1 $2" Reset $@ to one/two/three — prints 'one two'.
set -o pipefail; false | true; echo $? Prints 1 — without pipefail it would be 0.
Gotcha
'set -e' has surprising exceptions: it does NOT trigger on failures in conditions (if/while/&&/||) or on the left side of a pipe (needs pipefail). 'set -u' with unquoted "${arr[@]}" of an empty array errors in bash <4.4 — use "${arr[@]:-}" to be safe.
Related
trap
Registers a command to run when the shell receives a signal or special event (EXIT, ERR, DEBUG, RETURN). The workhorse for cleanup handlers, temp-file removal, and error diagnostics in scripts.
unset
Removes a variable or function from the shell — different from setting it to empty. Without a flag it targets variables first, then functions, unless -f or -v is specified.
shift
Renames positional parameters: $2 becomes $1, $3 becomes $2, and so on, decrementing $#. Optional N shifts by N positions and is common in manual argument parsing loops.