I'd like to make sure that at a certain point of a script, after source
ing a configuration file, several variables are set and, if they are not, to stop execution, telling the user about the missing variable. I have tried
for var in $one $two $three ; do
...
but if for example $two
is not set, the loop is never executed for $two
.
The next thing I tried was
for var in one two three ; do
if [ -n ${!var} ] ; then
echo "$var is set to ${!var}"
else
echo "$var is not set"
fi
done
But if two is not set, I still get "two is set to" instead of "two is not set".
How can I make sure that all required variables are set?
Update/Solution: I know that there is a difference between "set" and "set, but empty". I now use (thanks to https://stackoverflow.com/a/16753536/3456281 and the answers to this question) the following:
if [ -n "${!var:-}" ] ; then
so, if var
is set but empty, it is still considered invalid.
set -u
to the beginning of your script to terminate it immediately when an unset variable is used. – n.st Mar 25 '14 at 16:44