Saturday, June 23, 2012

How to test for an empty env var in a shell script

Recently, I came across one of my own bash scripts that goes way back. It relies on an environment variable being set, and if not, the script exits without a warning. I learned that the most elegant way to test if an environment variable is empty or unset is this:
 
# ${parameter:?word}
#
: ${BUILDDIR:?"Need to set BUILDDIR non-empty"}  

Here, if parameter ($BUILDDIR) is empty or unset, the expansion of word is written to the standard output and shell exits. The entire expression is an argument to the "colon command" (:) which simply evaluates its argument. According to UNIX historians, it is a derelict of good old days of the Bourne shell scripts which had every command start with colon.

No comments:

Post a Comment