Enabling error detection makes it much easier to detect problems in the script early:
set -o errexit
Exit script on first error. That way you avoid continuing on to do something which depended on something earlier in the script, perhaps ending up with some weird system state.
set -o nounset
Treat references to unset variables as errors. Very important to avoid running things like rm -you_know_what "$var/"
with an unset $var
. If you know that the variable can be unset, and this is a safe situation, you can use ${var-value}
to use a different value if it's unset or ${var:-value}
to use a different value if it's unset or empty.
set -o noclobber
It's easy to make the mistake of inserting a >
where you meant to insert <
, and overwrite some file which you meant to read. If you need to clobber a file in your script, you can disable this before the relevant line and enable it again afterwards.
set -o pipefail
Use the first non-zero exit code (if any) of a set of piped command as the exit code of the full set of commands. This makes it easier to debug piped commands.
shopt -s nullglob
Avoid that your /foo/*
glob is interpreted literally if there are no files matching that expression.
You can combine all of these in two lines:
set -o errexit -o nounset -o noclobber -o pipefail
shopt -s nullglob