Friday, February 2, 2007

Check whether $ENV_VAR is set or not

If you want to see whether a particular env var is set or not set, write something like this in your script

$ if (set -u; : $HOME) 2> /dev/null
> then
> echo "HOME env is set"
> else
> echo "Not"
> fi

A simple alternative

$ [ ! -z $HOME ] && echo "set" || echo "not"

1 comment:

Unknown said...

We have to be careful while checking for variables existence, because they can come from different sources and their names can collide. IOW, we might run into a "false positive" when we just interrogate a variable for it's size, like as,

[ ! -z "$ENV_VAR" ] && echo set || echo not
because, maybe a shell variable by the name ENV_VAR is set to a nonnull value
and when there is no env variable named ENV_VAR in the env pool. But using the
above check we will see the value "set" returned to us. That's a false positive.

just checking for a variable value length and finding it to be zero can be due to any of the reasons: either the said variable is unset or it's set to null.

### code to sanitize the environment variable ENV_VAR
if env | cut -d= -f1 | grep -qw ENV_VAR
case ${ENV_VAR-} in
'') echo >&2 "env var ENV_VAR exists but is null.";;
* ) echo >&2 "env var ENV_VAR exists and is nonnull.";;
echo >&2 "env var. ENV_VAR does not exist."
case ${ENV_VAR++} in
+) echo >&2 "However, detected a shell var. with the same name ENV_VAR";;

© Jadu Saikia