数组元素出乎意料地表现

时间:2017-11-19 23:53:44

标签: arrays bash

我正在尝试学习Bash语法。正如我阅读的文档所证实的那样,我希望ARRAYNAME [0]访问元素1和ARRAYNAME [1]来访问元素2.但是,我的脚本似乎发生了一些有趣的事情。试图访问ARRAYNAME [0]似乎给了我一个空字符串,因为我在下面的评论中显示输出 我编辑的以下脚本是为了使输出打印出我的预期。我不认为我的问题来自于zsh,因为我已尝试使用/bin/sh运行此脚本。我在这里看不到什么? 提前谢谢。

Test.sh:

#!/bin/zsh
NAMES=(Homer Marge Bart Lisa Maggy)
OUTPUTSTRING="The Simpsons family consists of: "
FAMILY="This list is empty :("
echo "Names[0]: ${NAMES[0]}"           # prints "Names[0]: "
echo "Names[1]: ${NAMES[1]}"           # prints "Names[1]: Homer"
if [ ${#NAMES[@]} -gt 0 ] ; then
    FAMILY="${NAMES[1]}"
else                                   # does not go in to else
    echo "$OUTPUTSTRING""$FAMILY" 
    exit 0
fi
NAMECOUNTER=2
while [ $NAMECOUNTER -le ${#NAMES[@]} ]; do      #-lt if behaviour was as I expected
    FAMILY+=", ${NAMES[$NAMECOUNTER]}"
    NAMECOUNTER=$((NAMECOUNTER+1))
done

echo "The Simpsons family consists of: $FAMILY"   # The Simpsons family consists of: Homer, Marge, Bart, Lisa, Maggy

1 个答案:

答案 0 :(得分:2)

您正在执行bash脚本(期望从0开始索引数组)和zsh(从1开始索引数组)。将shebang改为

#!/bin/bash

(或任何路径正确),以确保在将脚本作为可执行文件运行时由bash执行脚本。或者,使用myscript使用bash显式运行bash myscript,而不是./myscript