Shell strict mode

Make the shell stricter by default using set built-in.

Recommended defaults

Note: Do not attempt to use this in profile for a remote SSH server, as unbound variables will cause the login to fail and you can get locked out. Only attempt to ever enable this mode on a local machine, where you can disable strict mode easily.

For bash scripts, this one-liner can be placed under the shebang line. Take out the -E flag for zsh.

set -Eeu -o pipefail

Exit immediately when a command fails.

# > set -e
set -o errexit

Treat unset variables as an error and exit immediately.

Note: Bash 4 can have issues with this setting.

# > set -u
set -o nounset

The bash shell normally only looks at the exit code of the last command of a pipeline. This behavior is not ideal as it causes the -e option to only be able to act on the exit code of a pipeline’s last command. This is where -o pipefail comes in. This particular option sets the exit code of a pipeline to that of the rightmost command to exit with a non-zero status, or to zero if all commands of the pipeline exit successfully.

set -o pipefail

Print each command before executing. This command is great for scripts but too noisy when added to profile.

# > set -x
set -o xtrace

Bash only: Catch ERR traps properly. These won’t fire in certain scenarios when the -e flag is set.

# > set -E
set -o errtrace

See also:


shopt -s failglob
shopt -s globstar
shopt -s nullglob

See also: