TIL: Checking if an environment variable is set and exists

I’ve seen a lot of documentation for checking if a variable is set by calling [[ !-z "$VARNAME" ]]. That condictional statement essentially checks to see if the resolved string "$VARNAME" is not an empty string. Not very straight forward is it?

However, I found there is a new (well to me) conditional statement to confirm that the variable is set without all of this. It’s -v.

From the documentation:

-v varname

True if the shell variable varname is set (has been assigned a value).

Bash Conditional Expressions (Bash Reference Manual)


$ [[ -v TEST_VAR ]] && echo "nope"
#(Nothing is shown)
$ export TEST_VAR="asdf"         
$ [[ -v TEST_VAR ]] && echo "set var"
set var

Note: Not sure why the formatting is doing that. But the &amp&amp above should just be &&