Reputation: 27
I have a basic bash scripting question. The output of this script, I expected to be:
a y b x c y
but instead, I get:
a x b x c x
#!/bin/bash
for foo in 'a' 'b' 'c'; do
echo $foo;
if [ "$foo"=="b" ]; then
echo x;
else
echo y;
fi
done;
What am I missing?
Upvotes: 2
Views: 1288
Reputation: 101
Take a look at the following:
#!/bin/bash
for foo in 'a' 'b' 'c'; do
echo $foo;
if [ $foo == "b" ]; then # Make a note of the spaces
echo "x";
else
echo "y";
fi
done;
Regards,
Rohan Dsouza
Upvotes: 0
Reputation: 400682
You need to add spaces around the ==
operator, otherwise it gets parsed as the single token a==b
(after expansion, for the first iteration). This gets passed to the test
builtin (for which [
is an alternative name). Since the single argument a==b
is a non-empty string atom, it succeeds and exits with a status of 0, and the then
branch gets executed.
Upvotes: 2
Reputation: 298582
Try this script:
#!/bin/bash
for foo in 'a' 'b' 'c'; do
echo "$foo";
if [ "$foo" = 'b' ]; then
echo 'x';
else
echo 'y';
fi
done;
You use =
for string comparisons in bash. Also, quote your echo
'd strings.
Upvotes: 3