0

In the following example, I find that the if [ $aaa==x ] condition is always true.

for aaa in {x,y} 
do 
echo ---------
echo $aaa;
if [ $aaa==x ]
then echo this is x
elif [ $aaa==y ]
then echo this is y
fi
echo $aaa;
done;

That is, I always get the output as:

---------
x
this is x
x
---------
y
this is x
y

Even if I replace == with =, the problem remains. Why?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
pfc
  • 1,831
  • 4
  • 27
  • 50
  • Possible duplicate of [How to compare strings in Bash](https://stackoverflow.com/questions/2237080/how-to-compare-strings-in-bash) – Benjamin W. Sep 30 '19 at 15:02

1 Answers1

3

When you do:

if [ $aaa==x ]

You are expanding the parameter $aaa, then concatenating two = and the letter x, then testing whether this is a non-empty string (it always is).

if [ "$aaa" = x ]

Does what you want. Each part of the test should be passed as a separate argument, separated by whitespace.

Note that == isn't the standard syntax, you should use = to test whether two strings are equal.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141