Validating Variables in the Script Shell
What is the best way to make sure all the environment variables I need for my script have been set? I currently have a few if statements that are 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?
+2
source to share
4 answers
you can shorten them significantly:
[ -z "$FOO" ] && echo "FOO is empty"
[ -z "$BAR" ] && echo "BAR is empty"
The best way:
${FOO:?"FOO is null or not set"}
${BAR:?"BAR is null or not set"}
Of course, if the number of variables you intend to test is small, the loop suggested by @Aviator can be helpful to avoid repeating your code.
In response to @Aviator's answer, I would suggest defining a well-commented variable containing a list of variables to check. This way you don't make your code cryptic.
TEST_FOR_IS_SET="FOO BAR BAZ"
+1
source to share
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 am using it in code like this:
varsSet VAR1 VAR2 VAR3 || <error handling here>
+1
source to share