在shell脚本中使用数组

时间:2014-12-16 10:38:12

标签: arrays shell

我正在尝试在shell脚本中初始化一个数组,如下所示

declare -a testArr=( 'A' 'B' )

同样如下

testArr=( 'A' 'B' )

但在这两种情况下,我都会收到以下错误

shell1.sh: 1: shell1.sh: Syntax error: "(" unexpected

有人可以告诉我上述错误的原因吗?

1 个答案:

答案 0 :(得分:2)

由于你想使用POSIX shell而POSIX shell不支持数组,你可以用这种方式“模拟”数组:

set -- 'A' 'B'

然后你将拥有POSIX shell(“$ @”)中唯一包含A($ 1)和B($ 2)的“数组”。

您可以将此数组传递给另一个函数,例如:

test() {
    echo "$2"
}

set -- 'A' 'B C'
test "$@"

如果需要保存阵列,可以使用以下功能:

arrsave() {
    local i
    for i; do
        printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"
    done
    echo " "
}

并按以下方式使用它:

set -- 'A' 'B C'

# Save the array
arr=$(arrsave "$@")

# Restore the array
eval "set -- $arr"