What are the advantages and disadvantages of using set -u (or set -o nounset)?

Bash (like all other Bourne shell derivatives) has a feature activated by the command set -u (or set -o nounset). When this feature is in effect, any command which attempts to expand an unset variable will cause a fatal error (the shell immediately exits, unless it is interactive).

This feature is rather controversial, and has many extremely vocal advocates and opponents. It is designed to catch typos (misspelled variable names). However, it also triggers on many false positives, unless scripts are rewritten explicitly with set -u in mind. It is not always safe to add to the top of a script.

Positives

Advocates of set -u say the following:

Negatives

Opponents of set -u say the following:

Rewriting scripts to deal with it

If you want to use set -u, you may have to rewrite portions of your script, to avoid having it trigger on false positives. For the most part, this involves identifying which parameter expansions should be "ignored", and protecting them with a construct such as this:

while [ "$1" ]; do ...         # Triggers fatal error with -u

while [ "${1-}" ]; do ...      # Avoids fatal error with -u

explanation for the parameter expansion

BashFAQ/112 (last edited 2016-12-12 16:09:48 by JarnoSuni)