check if environment variable is already set

linux, shell, unix

Solution

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

Problem

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 ?

Original source

Related problems