views:

134

answers:

4

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" ]
then
    echo VAR1 not set
    exit
fi

if [ -z "$VAR2" ]
then
    echo VAR2 not set
    exit
fi

if [ -z "$VAR3" ]
then
    echo VAR3 not set
    exit
fi

Is there a better way?

+1  A: 

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.

TEST_FOR_IS_SET="FOO BAR BAZ"

AlberT
+2  A: 

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

Aviator
Thanks! I wont suggest this in future. I was also not sure. Just asked :)
Aviator
Wow!! Then will this work??
Aviator
plz edit your answer, I misunderstood it and erroneously downvoted. Edit in order to make me remove my vote
AlberT
I would also use a for loop for this, helps cut down on repeating yourself.
Andre Miller
Edited.. :).. Thanks Andre!! :)
Aviator
+1 for me too. That's ok now ? ;)
AlberT
lol! gladly! Since that also will work :)
Aviator
+3  A: 

You can use indirection:

vars="FOO BAR"
for var in $vars
do
    [[ -z ${!var} ]] && 
        echo "Variable ${var} is empty" ||
        echo "The value of variable ${var} is ${!var}"
done
Dennis Williamson
Exactly what i meant! Great!!+1
Aviator
Note that this tests if empty, not if it is set
AlberT
+1  A: 

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
varsSet()
{
        local var
        for var ; do
                eval "[ -n \"\$$var\" ] || return 1"
        done
}

I use it in code like this:

varsSet VAR1 VAR2 VAR3 || <error handling here>
camh