Check if an environment variable is defined

From raju

zsh

There are two ways to check if an environment variable is defined from a shell script. The results between the two differ when the environment variable is set to null.

ztest

% cat check_env_var_ztest.zsh 
#! /usr/bin/env zsh

if [ -z $KAMA ]; then
    echo "KAMA is not set"
else
    echo "KAMA is set"
fi

if [ ! -z $PWD ]; then
    echo "PWD is set"
else
    echo "PWD is not set"
fi

Sample run

% chmod +x check_env_var_ztest.zsh

% ./check_env_var_ztest.zsh 
KAMA is not set
PWD is set

 % KAMA=raju ./check_env_var_ztest.zsh
KAMA is set
PWD is set

 % KAMA= ./check_env_var_ztest.zsh 
KAMA is not set
PWD is set

braces

% cat check_env_var_braces.zsh
#! /usr/bin/env zsh

# man zshexpn(1)
#    ${+name}
#        If name is the name of a set parameter `1' is substituted, otherwise
#        `0' is substituted.

print '${+KAMA} = ' ${+KAMA}
print '${+PWD} = ' ${+PWD}

Sample run

% chmod +x ./check_env_var_braces.zsh

% ./check_env_var_braces.zsh 
${+KAMA} =  0
${+PWD} =  1

 % KAMA=raju ./check_env_var_braces.zsh
${+KAMA} =  1
${+PWD} =  1

 % KAMA= ./check_env_var_braces.zsh 
${+KAMA} =  1
${+PWD} =  1

Related links