2

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?

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what i meant! Great!!+1
Note that this tests if empty, not if it is set
2

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

3 Comments

Thanks! I wont suggest this in future. I was also not sure. Just asked :)
plz edit your answer, I misunderstood it and erroneously downvoted. Edit in order to make me remove my vote
I would also use a for loop for this, helps cut down on repeating yourself.
1

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>

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.