Bash混合for循环,如果那时表达给出不好的结果

时间:2014-03-15 15:31:07

标签: linux bash shell if-statement for-loop

我是linux shell和脚本的初学者,在做这个时我得到了一些奇怪的结果

#!/bin/bash

sysarch=( "x86" "amd64" )

arch_options=""
for i in "${sysarch[@]}"
do
    :
    if [ $i=="amd64" ]; then
        arch_options="-m64 -D ACIS64"
    elif [ $i=="x86" ]; then
        arch_options="-m32"
    fi
    echo $arch_options
done

exec $SHELL

所以,我有一个包含两种架构类型的数组。我遍历它们,我想为每个选项获得相应的GCC选项。问题是$arch_options总是"-m64 -D ACIS64",无论$i如何,我都不明白为什么。

1 个答案:

答案 0 :(得分:1)

就像你说的,它每次打印相同的值:

$ ./foo
-m64 -D ACIS64
-m64 -D ACIS64

让我们来看看它:

$ shellcheck foo
In foo line 9:
    if [ $i=="amd64" ]; then
         ^-- SC2077: You need spaces around the comparison operator.

In foo line 11:
    elif [ $i=="x86" ]; then
           ^-- SC2077: You need spaces around the comparison operator.

In foo line 17:    
exec $SHELL
     ^-- SC2086: Double quote to prevent globbing and word splitting.

并解决问题:

#!/bin/bash

sysarch=( "x86" "amd64" )

arch_options=""
for i in "${sysarch[@]}"
do
    :
    if [ $i == "amd64" ]; then
        arch_options="-m64 -D ACIS64"
    elif [ $i == "x86" ]; then
        arch_options="-m32"
    fi
    echo $arch_options
done

exec "$SHELL"

瞧:

$ ./foo
-m32
-m64 -D ACIS64