bash 如何在bash中将元素存储到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13007360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:36:06  来源:igfitidea点击:

How to store elements to an array in bash

arraysbashstore

提问by john doe

I got again tiny problem I would like to store strings in array I got following code:

我又遇到了一个小问题,我想将字符串存储在数组中,我得到了以下代码:

echo -e "Enter an amount"
read n 
for  ((i=0;i<n;i++)); 
do 
echo "Enter number $i " 
read ${array[$i]} 
done 
echo -e "$array[@]}"

Can you have a quick look a help me ? Thanks

你能帮我快速看看吗?谢谢

回答by ShankarG

Line 5 should probably read as:

第 5 行应该读作:

read array[$i]

${array[$i]}, which is what you have at present, will output the value of the element of the array with the subscript $i. The readcommand reads user input into a specified variable, so you need to specify the variable name.

${array[$i]},这就是你目前所拥有的,将输出带有下标$i的数组元素的值。该read命令将用户输入读取到指定的变量中,因此您需要指定变量名称。

回答by glenn Hymanman

you could also write

你也可以写

array=()
for ?((i=0; i<n; i++)); do 
    read -p "Enter number $i " 
    array+=($REPLY)
done