Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

zsh

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.

like image 578
paulmelnikow Avatar asked Mar 07 '17 18:03

paulmelnikow


People also ask

How do you check if a variable is set?

'-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.

How do I know if shell variable is set?

To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command.

How do I check if a variable is undefined in shell?

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"


2 Answers

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
like image 70
5 revs, 2 users 93% Avatar answered Oct 21 '22 15:10

5 revs, 2 users 93%


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
like image 25
chepner Avatar answered Oct 21 '22 13:10

chepner