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

时间:2021-10-28 19:34:24

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

你能快速帮我一下吗?谢谢

2 个解决方案

#1


3  

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 read command reads user input into a specified variable, so you need to specify the variable name.

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

#2


1  

you could also write

你也可以写

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

#1


3  

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 read command reads user input into a specified variable, so you need to specify the variable name.

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

#2


1  

you could also write

你也可以写

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