What it does
set -OPTION turns an option on, set +OPTION turns it off. In scripts the most used line is set -euo pipefail (stop on errors, error on unset variables, fail on broken pipes). set -- a b c sets $1 $2 $3. Without arguments, set prints all shell variables and functions.
How to write it
set [-abefhkmnptuvxBCEHPT] [-o OPTION] [--] [ARGUMENT]...Options 23
Most used
Nothing matches this filter.
Examples 10
$ run as a normal user# run as root (or with sudo)
1Strict mode for scripts
head -2 /usr/local/bin/backup.sh #!/bin/bash set -euo pipefailMany hidden errors become visible.
2Trace part of a script
set -x; cp a b; set +x + cp a bOnly these lines are traced.
3Stop on errors
bash -c 'set -e; false; echo "not reached"'The script ends at false.
4Unset variable error
bash -c 'set -u; echo "$TYPO"' bash: line 1: TYPO: unbound variableCatches typos like rm -rf "$DIR/" with an empty DIR.
5Pipe failures
bash -c 'set -o pipefail; false | true; echo $?' 1Without pipefail the result would be 0.
6Do not overwrite files
set -C; echo x > existing.txt bash: existing.txt: cannot overwrite existing fileProtects against a wrong >.
7vi mode on the command line
set -o viEsc, then vi keys to edit.
8Show all options
set -o | headon/off for each.
9Set positional parameters
set -- one two three; echo "$2 / $#" two / 3Useful in tests and functions.
10List variables and functions
set | grep ^HISTAll HIST variables.
Nothing matches this filter.
Exit codes
0 | Done. |
1 | Wrong option. |