Every example here was run on macOS’s /bin/bash (3.2.57) and on Homebrew’s bash (5.3.15). Where the two disagree, the example was also run on Linux in Docker’s official bash images, 4.3, 4.4 and 5.2.
The set builtin
set turns shell options on with - and off with +. Each short flag has a long name for -o, so set -e and set -o errexit are the same thing, and set +e turns it off again. Short flags combine, as in set -eu; pipefail has no short form, so it is always written -o pipefail.
set -o lists every option and whether it is on. set +o prints the same list as commands that would restore it, which is how to save the state around a block that changes it:
$ bash -c 'set -euo pipefail; set +o' | grep -E 'errexit|nounset|pipefail|noclobber'
set -o errexit
set +o noclobber
set -o nounset
set -o pipefail
$- holds the short flags currently on (ehuBc after set -euo pipefail in a bash -c), and $SHELLOPTS holds the long names, colon-separated.
With arguments after --, set replaces the positional parameters instead:
$ bash -c 'set -- a "b c"; echo $#; printf "<%s>" "$@"'
2
<a><b c>
-e (errexit)
set -e ends the script when a command returns a non-zero status:
set -e
false
echo after # never runs; the script exits with status 1
It is suspended while a command runs as the condition of an if, while or until, after !, or anywhere in an && or || list except the last command. The suspension covers everything that command calls, so a function whose second line depends on its first carries on past a failure:
set -e
f() { false; echo "f carried on"; }
if f; then :; fi # prints "f carried on"
false && true # fails, and the script continues
local returns its own status, not the status of the substitution it assigns:
set -e
g() { local x=$(false); echo "local masked it"; }
g # prints "local masked it"
Declaring and assigning on separate lines (local x; x=$(false)) restores the check. A plain x=$(false) ends the script, because an assignment’s status is the substitution’s.
Inside a command substitution set -e is off, so x=$(false; echo "carried on") sets x to “carried on” and the script continues. shopt -s inherit_errexit carries the setting into substitutions, and with it the same line ends the script. The option exists in bash 4.4 and later; 4.3 and 3.2 reject the name.
It also fires on commands whose non-zero status is an answer rather than a failure. grep -c counts matches and exits 1 when the count is zero, so this ends the script before the zero can be used:
set -e
c=$(printf 'a\n' | grep -c zzz) # script ends here, status 1
An arithmetic command returns 1 when its result is zero, and a post-increment’s result is the old value. n=0; ((n++)) ends the script on every 4.x and 5.x bash tried and does not end it on 3.2, so the same script stops on a Linux CI runner and carries on with a Mac’s stock bash. n=$((n + 1)) is an assignment and never fails.
Where a non-zero status is an expected answer, put the command in an if, or add || true and read the result on the next line:
if go test ./...; then result=ok; else result=fail; fi
count=$(grep -c PASS log.txt || true)
-u (nounset)
set -u makes expanding an unset variable an error:
$ cat u.sh
set -u
echo "hello $NAME"
echo after
$ bash u.sh
u.sh: line 2: NAME: unbound variable
The script exits with status 1. Without the flag, $NAME expands to nothing, and rm -rf "$BUILD_DIR/" with a misspelt variable name becomes rm -rf "/".
Positional parameters count, so "$1" in a script called with no arguments is an error too. A default makes the expansion legal: ${NAME:-} gives an empty string when the variable is unset or empty, ${NAME-fallback} gives “fallback” only when it is unset, and ${1:-world} is the usual way to take an optional argument.
Expanding an empty array with "${a[@]}" is an “unbound variable” error on bash 3.2 and 4.3 and expands to nothing on 4.4 and later, so a script written against a current Linux bash can fail on a Mac’s stock bash. ${a[@]+"${a[@]}"} works on all of them.
-o pipefail
A pipeline’s status is normally the status of its last command, so a failure earlier in the pipe disappears:
$ bash -c 'false | true; echo $?'
0
$ bash -c 'set -o pipefail; false | true; echo $?'
1
With pipefail the pipeline returns the status of the rightmost command that failed, so (exit 3) | (exit 5) | true returns 5. Without it, curl https://example.com/data | jq . reports success when curl fails, because jq succeeded at reading nothing. ${PIPESTATUS[@]} holds every command’s status from the last pipeline either way: false | true | (exit 4) leaves it as 1 0 4.
A reader that stops early fails the pipeline. yes | head -1 returns 141: head exits after one line, yes is killed by SIGPIPE on its next write, and 141 (128 plus signal 13) becomes the pipeline’s status. With set -e as well, that ends the script.
-x (xtrace)
set -x prints each command to standard error after expansion and before it runs, prefixed with +. set +x turns it off, and is itself the last line traced:
$ bash -c 'set -x; name=world; echo "hello $name"; set +x; echo quiet'
+ name=world
+ echo 'hello world'
hello world
+ set +x
quiet
The prefix is the variable PS4, expanded for each line, so it can carry the file and line number:
$ cat x.sh
PS4='+ ${BASH_SOURCE}:${LINENO}: '
set -x
name=world
echo "hello $name"
$ bash x.sh
+ x.sh:3: name=world
+ x.sh:4: echo 'hello world'
hello world
bash -x script.sh traces a script without editing it.
-v (verbose)
set -v prints each line as it is read, before expansion, so echo "$HOME" is shown as written rather than with the path filled in. For debugging it shows less than -x, because it shows the source rather than what ran.
-n (noexec)
set -n reads commands without running them. Used as bash -n script.sh, it checks a script’s syntax:
$ cat n.sh
echo start
if true then
echo inside
fi
$ bash n.sh
start
n.sh: line 4: syntax error near unexpected token `fi'
$ bash -n n.sh
n.sh: line 4: syntax error near unexpected token `fi'
Run normally, the script executed its first line before reaching the error. Under -n nothing ran. It finds syntax errors only: a misspelt command name or a wrong path passes.
-C (noclobber)
set -C makes > fail on a file that already exists:
$ cat c.sh
set -C
echo one > out.txt
echo two > out.txt
echo "status $?"
cat out.txt
echo three >| out.txt
cat out.txt
$ bash c.sh
c.sh: line 3: out.txt: cannot overwrite existing file
status 1
one
three
>| overwrites regardless, and >> still appends. Under set -e the failed redirection ends the script. It is more often set in an interactive shell’s profile than in a script, to stop a mistyped > replacing a file, and anything run in a shell that has it on fails wherever it uses > on a file it means to replace.
-f (noglob)
set -f turns off filename expansion, so * and ? stay literal:
$ bash -c 'set -f; echo *.sh; set +f; echo *.sh'
*.sh
run.sh
It suits a script that passes patterns through to another program, such as a list of find -name arguments held in a variable.
-a (allexport)
set -a exports every variable assigned while it is on:
$ bash -c 'FOO=bar; bash -c "echo child sees [\$FOO]"'
child sees []
$ bash -c 'set -a; FOO=bar; bash -c "echo child sees [\$FOO]"'
child sees [bar]
The common use is loading a file of NAME=value lines into the environment of the commands that follow: set -a; . ./settings.env; set +a.
-E (errtrace)
trap '...' ERR runs a command whenever a command fails under the same rules set -e uses, which makes it the place to report where a script stopped:
set -e
trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR
cp /nonexistent /tmp/
cp: /nonexistent: No such file or directory
failed at line 3: cp /nonexistent /tmp/
Functions do not inherit the trap. With the same cp moved into a function, the script still stops but the trap prints nothing. set -E makes functions, command substitutions and subshells inherit it. Inside a function, bash 3.2 reports the function’s first line in $LINENO where 5.3 reports the line that failed.
A default
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit 2>/dev/null || true
trap 'echo "${BASH_SOURCE}:${LINENO}: \"${BASH_COMMAND}\" failed" >&2' ERR
if [[ -n ${TRACE:-} ]]; then set -x; fi
-e, -u and pipefail stop the script at a failed command, an unset variable and a failed stage in a pipe. -E and the ERR trap say which line stopped it. inherit_errexit carries -e into command substitutions on 4.4 and later and is skipped on older bash. TRACE=1 ./script.sh turns on tracing without an edit.
The header does not make a script safe on its own. Every command whose non-zero status is an answer rather than a failure (a grep that finds nothing, a test that fails, an arithmetic result of zero) still needs an if or a || true that the next line reads.