Shell(sh)脚本数组

时间:2017-10-10 09:11:06

标签: arrays sh ash

一直试图在sh shell脚本中找到做数组。除了BASH等之外,除了sh不支持的数组之外,还没有找到太多。

以下是我使用setvar和eval提出的问题。有没有更好的办法?有什么方法可以消除setvar和/或eval?

#!/bin/sh
# FreeBSD 11.1

# Kind of an array workaround.

echo -e "Simulated array creation and element assignment using dynamic index."
array() {
    i=0
    for x in $2
    do
        setvar ${1}_${i} $x    # any way to do without setvar?
        i=$((i+1))
    done
    setvar ${1}_cnt $i
}

array "my_arry" "a b c"

echo -e "\nSimulated array element access using dynamic index."
i=0
while [ $i -lt $my_arry_cnt ]
do
    eval aev=\${my_arry_${i}}    # any way to do without eval?
    i=$((i+1))
    echo $aev
done

echo -e "\nSimulated array element access using static index."
echo ${my_arry_0}
echo ${my_arry_1}
echo ${my_arry_2}

0 个答案:

没有答案