Charles Nobbert
Charles Nobbert

Reputation: 27

bash scripting basic string comparison

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

Answers (3)

Rohan Dsouza
Rohan Dsouza

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

Adam Rosenfield
Adam Rosenfield

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

Blender
Blender

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

Related Questions