为什么我的 for 循环打印了这么多结果?

Why is my for loop printing so many results?

我正在学习 for 循环。这是我的代码:

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

这是我 运行 时的输出:

Arizona rocks
Arizona rocks
Arizona rocks
Arizona rocks

为什么输出了4次还是错误的答案?

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

这有效

试试这个:

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

我做的修改是:

  • for state in "${states[@]}":双引号很关键,因为您有一个数组元素带有 space.

  • 您的代码在 4 个项目上循环:

      New
      York
      Arizona
      Texas
    
  • 并且我将您的 if 语句修改为 if [[ "$state" == 'New York' ]]。如果其中有 space,$state 上的双引号可确保您正确处理该值。任何变量都应该在 " ".

  • 要调试这些东西,请在 for 循环中添加 echo "$state" 以查看它在做什么。