Search code examples
bashloopsfor-in-loop

Why is my for loop printing so many results?


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?


Solution

  • 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.