set Command Cheat Sheet
set is a shell builtin that allows you to change the values of shell options and set the positional parameters.
It is critical for writing robust and safe bash scripts.
Synopsis
set [options] [arguments]
Critical Script Safety Options
Fail on Error (-e)
Exit immediately if a command exits with a non-zero status.
set -e
cd /important/dir fails, potentially deleting the wrong files.
Treat Unset Variables as Error (-u)
Exit if you try to use an undefined variable (e.g., $UNDEFINED).
set -u
rm -rf /$DIR being interpreted as rm -rf / if $DIR is empty.*
Fail inside Pipes (-o pipefail)
If any command in a pipeline fails, the whole pipe fails. (Normally, only the last command's exit code matters).
set -o pipefail
The "Unofficial Bash Strict Mode" header
Put this at the top of your scripts:
#!/bin/bash
set -euo pipefail
Debugging
Print Commands (-x)
Print each command to stderr before executing it (Trace mode).
set -x
ls -la
# Output: + ls -la
To turn off:
set +x
Print Input Lines (-v)
Print shell input lines as they are read.
set -v
Positional Parameters
You can overwrite arguments ($1, $2...) currently in the shell.
set -- apple banana cherry
echo $1
# Output: apple
Other Options
- No Overwrite (
-C): Prevent output redirection from overwriting existing files.set -C echo "test" > existing_file.txt # Error: cannot overwrite existing file - Export All (
-a): Mark variables which are modified or created to be exported. - vi Mode:
set -o vi(Enable vi shortcuts on command line). - emacs Mode:
set -o emacs(Default).
Notes
- Current Settings: Running
setwithout arguments lists all shell variables and functions. - shopt:
setcovers POSIX options.shoptcovers Bash-specific options (likeglobstar).