How do I check if a variable is set in zsh?

The typical way to do this in Zsh is:

if (( ${+SOME_VARIABLE} )); then

For example:

if (( ${+commands[brew]} )); then
    brew install mypackage
else
    print "Please install Homebrew first."
fi

In Zsh 5.3 and later, you can use the -v operator in a conditional expression:

if [[ -v SOME_VARIABLE ]]; then

The POSIX-compliant test would be

if [ -n "${SOME_VARIABLE+1}" ]; then

Leave a Comment