Test if a variable is unset
For scalar variables, in standard (POSIX) sh
syntax:
if [ "${var+set}" != set ]; then
echo var is not set
fi
Or fancier albeit less legible things like
if [ -z "${var++}" ]; then
echo var is unset
fi
Or:
if ${var+false}; then
echo var is unset
fi
For array variables (not that arrays are portable), in zsh
or yash
, that would return unset unless the array is assigned any list including the empty list, while in bash or ksh that would return unset unless the element of index 0 is set. Same for associative arrays (for key "0").
Note that except in zsh
(when not in sh
emulation), export var
or readonly var
declares the variable but doesn't give it any value, so shells other than zsh
will report var
as unset
there (unless var
had been assigned a value before the call to export
/readonly
).