-1

I am learning about for loops. Here is my code:

#!/bin/bash

# states list

states=('New York' 'Arizona' 'Texas')

# script to check which state is cool. 

for state in ${states[@]}
do
    if [ $state = 'New York' ]
    then
        echo 'New York is cool' 
    else
        echo 'Arizona rocks'
    fi
done

This is my output when I run it:

Arizona rocks
Arizona rocks
Arizona rocks
Arizona rocks

Why is it outputting 4 times and also the wrong answer?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
TeaLeaf
  • 1
  • 2
  • You need to double-quote all variable (and array) references to avoid word-splitting. [shellcheck.net](https://www.shellcheck.net) is good at pointing this (and many other common errors) out. – Gordon Davisson Mar 04 '22 at 04:27
  • 1
    As an aside, a `set -x` at the top of your script (but after the shebang line) would probably have made the problem immediately obvious. – paxdiablo Mar 04 '22 at 06:46

2 Answers2

2

Try this:

#!/bin/bash

# states list
states=('New York' 'Arizona' 'Texas')
# script to check which state is cool.

for state in "${states[@]}"
do
    if [[ "$state" == 'New York' ]]
    then
        echo 'New York is cool'
    else
        echo 'Arizona rocks'
    fi
done

The modifications I made are:

  • for state in "${states[@]}": the double quotes are critical since you have one array element with a space.

  • Your code loops on 4 items:

      New
      York
      Arizona
      Texas
    
  • And I modified your if statement to if [[ "$state" == 'New York' ]]. The double quotes on $state ensure you properly process the value if there is a space in it. Any variable should be in " ".

  • To debug such things, add echo "$state" inside your for loop to see what it is doing.

Nic3500
  • 8,144
  • 10
  • 29
  • 40
  • 2
    Or use `bash -x script.sh` to see the action as it occurs. – Jonathan Leffler Mar 04 '22 at 04:22
  • Is it okay to have the variables of my states=( inside single ' ' ? Our should those be inside " " too. – TeaLeaf Mar 04 '22 at 17:55
  • Inside your declaration of the array elements, it is fine to use single quotes since it is plain text. Double quotes allow for variables interpolation. Look at this question for full details: https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash. – Nic3500 Mar 04 '22 at 20:57
-1
#!/bin/bash

# states list

states=("New York" "Arizona" "Texas")

# script to check which state is cool. 

for state in "${states[@]}"
do
    if [ "$state" = "New York" ] 
    then
        echo "New York is cool" 
    else
        echo "Arizona rocks"
    fi
done

this works

Yuriy Kirel
  • 105
  • 7
  • This may fix the problem but doesn't answer the question. Could you point out what changes you made and why? – Lance U. Matthews Mar 04 '22 at 04:32
  • 1
    Fixes without explanations are not usually a good idea. We're here to educate, not just fix. See Nioc3500's response for a good example. – paxdiablo Mar 04 '22 at 06:47