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.
'-v' or '-z' option is used to check the variable is set or unset. The above Boolean expression will return true if the variable is set and returns false if the variable is not set or empty. Parameter substitute is another way to check the variable is set or unset.
To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command.
To find out if a bash variable is defined: Return true if a bash variable is unset or set to the empty string: if [ -z ${my_variable+x} ]; Also try: [ -z ${my_bash_var+y} ] && echo "\$my_bash_var not defined"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With