Hacker News new | ask | show | jobs
by Stratoscope 3720 days ago
> I once deleted a /lib directory due to a misspelled variable in a script!

Ah yes, the old "rm -rf $TEMPBASEEDIR/lib" bug. It is so easy to have that happen.

Or like I did, write a script that assumes a certain environment variable is set outside the script... and then forget to set the variable before running it!

To prevent these problems, use "set -u" at the top of your bash scripts. This will halt the script instead of silently inserting an empty string if you use an undefined variable.

"set -e" (halt on nonzero return code) and "set -o pipefail" (propagate error returns through a pipe) are also useful options, or combine them with:

  set -euo pipefail
Here's a great article that describes these options and some tips for using them:

http://redsymbol.net/articles/unofficial-bash-strict-mode/

3 comments

But make sure you read up on the problems with `set -e` before you rely on it!

http://mywiki.wooledge.org/BashFAQ/105

That is a great article. I just strictified the cheeky shell scripts that automate deployment of my current project.
Yes; that was around the time I started using "set -u" with religious devotion.