dogbane
dogbane

Reputation: 274838

Validating Variables in Shell Script

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?

Upvotes: 2

Views: 2261

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 360685

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

Upvotes: 3

drAlberT
drAlberT

Reputation: 23258

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"

Upvotes: 1

camh
camh

Reputation: 42538

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>

Upvotes: 1

vpram86
vpram86

Reputation: 6010

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

Upvotes: 2

Related Questions