check if environment variable is already set [duplicate]

I am writing a shell script, where I have to check if environment variable is set, if not set then I have to set it. Is there any way to check in shell script, whether an environment variable is already set or not ?


The standard solution to conditionally assign a variable (whether in the environment or not) is:

: ${VAR=foo}

That will set VAR to the value "foo" only if it is unset.
To set VAR to "foo" if VAR is unset or the empty string, use:

: ${VAR:=foo}

To put VAR in the environment, follow up with:

export VAR

You can also do export VAR=${VAR-foo} or export VAR=${VAR:=foo}, but some older shells do not support the syntax of assignment and export in the same line. Also, DRY; using the name on both sides of the = operator is unnecessary repetition. (A second line exporting the variable violates the same principal, but feels better.)

Note that it is very difficult in general to determine if a variable is in the environment. Parsing the output of env will not work. Consider:

export foo='
VAR=var-value'
env | grep VAR

Nor does it work to spawn a subshell and test:

sh -c 'echo $VAR'

That would indicate the VAR is set in the subshell, which would be an indicator that VAR is in the environment of the current process, but it may simply be that VAR is set in the initialization of the subshell. Functionally, however, the result is the same as if VAR is in the environment. Fortunately, you do not usually care if VAR is in the environment or not. If you need it there, put it there. If you need it out, take it out.


[ -z "$VARIABLE" ] && VARIABLE="abc"

if env | grep -q ^VARIABLE=
then
  echo env variable is already exported
else
  echo env variable was not exported, but now it is
  export VARIABLE
fi

I want to stress that [ -z $VARIABLE ] is not enough, because you can have VARIABLE but it was not exported. That means that it is not an environment variable at all.


What you want to do is native in bash, it is called parameter substitution:

VARIABLE="${VARIABLE:=abc}"

If VARIABLE is not set, right hand side will be equal to abc. Note that the internal operator := may be replaced with :- which tests if VARIABLE is not set or empty.


if [ -z "$VARIABLE" ]; then
    VARIABLE=...
fi

This checks if the length of $VARIABLE is zero.