Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Prevent Unset Variables in Your Shell / Bash Scripts with set nounset

prevent-unset-variables-in-your-shell-bash-scripts-with-set-nounset.jpg

This is handy to prevent typos because this option will halt your script as soon as an unset variable is found.

Quick Jump:

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

Will you be setting this in all of your scripts? Let us know!

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments