2

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?

2
  • 2
    Sheesh, go easy on that whitespace... Commented Nov 1, 2011 at 18:46
  • OK. I figured it out. Having spaces between the operator makes a difference. Argh. Commented Nov 1, 2011 at 18:50

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Actually, it succeeds and the then branch is executed. With a single argument, test returns true if the argument is non-null, and a==b is a non-null string.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.