31

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.

Community
  • 1
  • 1
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
  • 1
    Possible duplicate of [How to check if a variable is set in Bash?](http://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash) – Jens Mar 07 '17 at 18:11
  • 1
    Huh. I mean, there *is* zsh-only syntax, but the POSIX sh syntax works here too. – Charles Duffy Mar 07 '17 at 18:11
  • 1
    Edited to clarify. The Bash question doesn't provide the canonical zsh syntax. – paulmelnikow Mar 07 '17 at 18:17
  • The linked question was asked (and mostly answered) before `bash` introduced the `-v` operator (which `zsh` also supports, see my answer). – chepner Mar 07 '17 at 18:30
  • I'm using OS X Sierra which ships with bash 3.2 and zsh 4.2, neither of which support `-v`. – paulmelnikow Mar 07 '17 at 18:47
  • 1
    The stock version of `bash` isn't really useful as anything other than a POSIX-compatible shell; it is *years* out of date. `/bin/zsh` should be 5.2 in OS X Sierra. – chepner Mar 07 '17 at 18:52
  • You're right, 5.2. That was a typo. – paulmelnikow Mar 07 '17 at 18:55

2 Answers2

42

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
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
16

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
chepner
  • 497,756
  • 71
  • 530
  • 681