Home > Enterprise >  Why is my for loop printing so many results?
Why is my for loop printing so many results?

Time:03-04

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?

CodePudding user response:

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

CodePudding user response:

#!/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

  • Related