[英]Filling a dynamic array with user input in shell scripting
I am new to shell scripting. 我是shell脚本的新手。 I am trying to create an array of size
n
, where n
is input by the user during the run time. 我正在尝试创建一个大小为
n
的数组,其中n
是在运行时由用户输入的。
while [ $i -lt $n ]
do
echo For person $i enter the name?
read io
eval Name[$index]= $io
done
When I try to do this, the values are overwritten every time the loop gets the input from user. 当我尝试这样做时,每次循环从用户获得输入时都会覆盖这些值。
For ex: if person 1 is - Tom,if person 2 is - John. 例如:如果第一个人是 - 汤姆,如果第二个人是 - 约翰。 Then when i try to print the names of all person at the end of the script, person 1 name is overwritten with person n th name.(which means, all names are stored in a single variable instead of an array).
然后,当我尝试在脚本末尾打印所有人的姓名时,第1个人的姓名将被第n个名称覆盖(这意味着,所有名称都存储在单个变量而不是数组中)。
Can someone tell me where am i going wrong? 谁能告诉我哪里出错了?
You need to increment i
in the loop so that it eventually exits. 你需要在循环中增加
i
,以便它最终退出。 This line increments i
by 1: 此行将
i
递增1:
let i+=1
You don't need to use eval
in eval Name[$index]= $io
. 您不需要在
eval Name[$index]= $io
使用eval
。
There is no variable named index
(at least not in your code sample). 没有名为
index
变量(至少在代码示例中没有)。 I assume you meant to use i
there. 我假设你打算在那里使用
i
。 (ie, Name[$index]
should be Name[$i]
) (即
Name[$index]
应为Name[$i]
)
This code works: 此代码有效:
#!/bin/sh -e
Name=()
i=0
while [ $i -lt 4 ]
do
echo For person $i enter the name?
read io
Name[$i]=${io}
let i+=1
done
echo names:
for n in "${Name[@]}"
do
echo $n
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.