Take the 2-minute tour ×

What is the best way to make sure that all the environment variables I need for my script have been set? Currently, I have multiple if-statements which is not very neat:

if [ -z "$VAR1" ]
    echo VAR1 not set

if [ -z "$VAR2" ]
    echo VAR2 not set

if [ -z "$VAR3" ]
    echo VAR3 not set

Is there a better way?

share|improve this question
add comment

4 Answers

up vote 3 down vote accepted

You can use indirection:

vars="FOO BAR"
for var in $vars
        echo "Variable ${var} is empty" ||
        echo "The value of variable ${var} is ${!var}"
share|improve this answer
Exactly what i meant! Great!!+1 –  vpram86 Sep 9 '09 at 9:23
Note that this tests if empty, not if it is set –  AlberT Sep 9 '09 at 9:39
add comment

Use a for loop in (set of variables u want). Won't that work?

share|improve this answer
Thanks! I wont suggest this in future. I was also not sure. Just asked :) –  vpram86 Sep 9 '09 at 9:12
Wow!! Then will this work?? –  vpram86 Sep 9 '09 at 9:12
plz edit your answer, I misunderstood it and erroneously downvoted. Edit in order to make me remove my vote –  AlberT Sep 9 '09 at 9:13
I would also use a for loop for this, helps cut down on repeating yourself. –  Andre Miller Sep 9 '09 at 9:13
Edited.. :).. Thanks Andre!! :) –  vpram86 Sep 9 '09 at 9:14
show 2 more comments

I have this function in my shell library:

# Check that a list of variables are set to non-null values.
# $@: list of names of environment variables. These cannot be variables local
#     to the calling function, because this function cannot see them.
# Returns true if all the variables are non-null, false if any are null or unset
        local var
        for var ; do
                eval "[ -n \"\$$var\" ] || return 1"

I use it in code like this:

varsSet VAR1 VAR2 VAR3 || <error handling here>
share|improve this answer
add comment

you can short them a lot:

[ -z "$FOO" ] && echo "FOO is empty"
[ -z "$BAR" ] && echo "BAR is empty"

a better way:

${FOO:?"FOO is null or not set"}
${BAR:?"BAR is null or not set"}

Of course if the number of variables you are going to test is not low, looping as suggested @Aviator maybe useful to avoid repeating code.

Upon @Aviator answer, I'd like to suggest to define a well commented variable containing a list of your variables-to-be-tested. This way you don't make your code cryptic.


share|improve this answer
add comment

Your Answer


