What is the canonical / idiomatic way to test if a variable has been set in zsh?
if ....something.... ; then
print "Sweet, that variable is defined"
else
print "That variable is not defined"
fi
Here's the SO answer for bash.
What is the canonical / idiomatic way to test if a variable has been set in zsh?
if ....something.... ; then
print "Sweet, that variable is defined"
else
print "That variable is not defined"
fi
Here's the SO answer for bash.
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
Use the -v
(introduced in zsh
5.3) operator in a conditional expression.
% unset foo
% [[ -v foo ]] && echo "foo is set"
% foo=
% [[ -v foo ]] && echo "foo is set"
foo is set