Test if multiple variables are set
Quoting error.
if [ -n "${!var}" ] ; then
For the future: Setting
set -x
before running the code would have shown you the problem. Instead of adding that to the code you can call your script with
bash -vx ./my/script.sh
Only thing you need are quotes in your test:
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
Works for me.
If you want the program stopped:
N=
${one?var 1 is unset}
${two:?var 2 is unset or null}
${three:+${N:?var 3 is set and not null}}
That'll do the trick. Each of the messages following the question mark is printed to stderr
and the parent shell dies. Well, OK, so not each message - only one - just the first one that fails prints a message cause the shell dies. I like to use these tests like this:
( for v in "$one" "$two" "$three" ; do
i=$((i+1)) ; : ${v:?var $i is unset or null...}
done ) || _handle_it
I had a lot more to say about this here.