在 shell 的变量中动态读取和存储值

Dynamically read and store values in variables in shell

我正在尝试这样做...

echo "Enter the number of fruits\n"
read fruit

echo $inp # this will print the number of fruits to enter

如果水果是 4

脚本应该能够动态地要求用户输入 [4] 个水果并将其存储到 4 个变量中,如下所示。

fruit1=apple
fruit2=jack fruit
fruit3=pineapple
fruit4=grapes

我尝试了下面的方法,但没有帮助

for i in `seq 1 $fruit`
                    do
                            echo "Enter fruit$i\n"
                            read fruit[$i]
                            echo "fruit[$i]"
                    done

提前致谢。

您可以在每一步动态地增加数组。假设你从计数开始,初始化空数组,然后一个一个添加元素。

count=4; fruits=(); 
for i in `seq "$count"`; 
       do read f; fruits+=( "$f" ); 
       done; 
echo "${fruits[@]}"

适用版本: 版本 AJM 93t+ 2010-06-21.

这适用于 AIX

中的 BASH

这是 ksh88- 和 pdksh 兼容的版本:

count=4
set -A fruits
i=0
while (( i < count )); do
    echo "Enter fruit$i"
    read fruits[i]
    (( i += 1 ))
done
echo "${fruits[@]}"

在 Solaris 8 上用 /bin/ksh (ksh88) 测试,在 MirBSD 上用 pdksh 测试(其本机 mksh 支持 +=() 符号,但我有其他为增量测试安装的外壳)。