Prevent Unset Variables in Your Shell / Bash Scripts with set nounset
This is handy to prevent typos because this option will halt your script as soon as an unset variable is found.
Imagine this scenario:
#!/usr/bin/env sh
REFERRER="youtube"
echo "${REFERER}"
That’s going to echo an empty string because the variable is defined as REFERRER but it’s referenced as REFERER (it’s missing the double “R"s).
If you’re a fan of using ShellCheck, it will
warn you of this but you can go the extra step and add set -o nounset
(or
set -u
) near the top of your script and now if you run it you’ll get ./demo: 7: REFERER: parameter not set
. The extra protection is nice and it’s POSIX
compliant.
If you want an optional variable that might be undefined, you can do that too:
#!/usr/bin/env sh
set -o nounset
DEBUG="${DEBUG:-}"
[ -n "${DEBUG}" ] && echo "A helpful debug message!"
Now you can run ./demo
or DEBUG=1 ./demo
without errors.
This is something I’ll be adding to all of my scripts.
# Demo Video
Timestamps
- 0:32 – ShellCheck can help us here but we can do better
- 0:43 – Protecting ourselves from variable typos with the nounset option
- 1:52 – Handling optional variables by setting an “empty” default
- 3:43 – Defining all of your variables is a good practice to adhere to
Reference Links
- https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
- https://nickjanetakis.com/blog/why-you-should-put-braces-around-your-variables-when-shell-scripting
Will you be setting this in all of your scripts? Let us know!