This question already has an answer here:
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:
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:
To put VAR in the environment, follow up with:
You can also do
export VAR=${VAR-foo}
orexport 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:Nor does it work to spawn a subshell and test:
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.
What you want to do is native in bash, it is called parameter substitution:
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.This checks if the length of $VARIABLE is zero.
I want to stress that
[ -z $VARIABLE ]
is not enough, because you can haveVARIABLE
but it was not exported. That means that it is not an environment variable at all.