Your question doesn’t make a lot of sense. First of all, if you say
one=1
two=""
three=3
four=""
for num in $one $two $three $four
do
︙
then the for
statement is interpreted as
for num in 1 3
and so there are only two iterations, with num
equal to 1
and 3
.
If you want to have four iterations,
with num
equal to 1
, (null), 3
and (null), then you need to say
for num in "$one" "$two" "$three" "$four"
You should quote shell variable references
unless you have a good reason not to,
and you’re sure you know what you’re doing.
So,
for num in "$one" "$two" "$three" "$four"
do
echo "num is $num"
done
will result in
num is 1
num is
num is 3
num is
Now, if you want the results to say 1
, 0
, 3
, 0
,
it’s a simple matter of saying
for num in "$one" "$two" "$three" "$four"
do
if [ "$num" = "" ]
then
num=0
fi
echo "num is $num"
done
Note that
- You must have whitespace before and after the
[
,
- You must have whitespace before and after the
=
,
- You must have whitespace before the
]
(and after it, if there’s anything else after it), and
fi
is if
spelled backwards.
But your question title mentions “unset variables”.
two
and four
are set to a blank string;
five
and six
(and orange
, pumpkin
, tiger
,
and a quasi-infinite list of other potential variable names)
are unset. There’s a difference.
If that is what you’re interested in,
you need to ask a different question, because, if you do
for num in "$one" "$two" "$three" "$four" "$five" "$six" "$orange" "$pumpkin" "$tiger"
do
︙
then it will be impossible to distinguish the five
, six
, orange
,
pumpkin
, and tiger
, iterations from the two
and four
iterations —
num
will be set to a blank string in all seven cases.
You would need to test the $four
and $five
(etc.) variables directly.
P.S. Don’t ask a new question; do a search.
This has been answered before.
WARNING: Drive-by question. OP created his (or her) account, asked this question 18 minutes later, and disappeared two minutes earlier (? question asked Dec 9 at 15:30; user Last seen Dec 9 at 15:28), apparently without taking the Tour. – Scott – 2015-12-19T11:29:49.897