arrays - Bash 中的数组 : Displaying all elements of array

标签 arrays linux bash shell

 echo "Enter N "   # enter N for number of inputs for the loop                                                         
 read N # reading the N
 #using c-style loop
 for((i=1;i<=N;i++))
 do
 read -a arr # arr is the name of the array
 done
 echo ${arr[*]} # 1 
 echo ${arr[@]} # 2   

尝试了所有方法来显示数组的所有元素,但没有获得所需的输出。它显示数组的最后一个元素。

最佳答案

为了能够在循环中填充数组,请使用:

arr+=("$var")

完整代码:

read -p 'Enter N: ' N

arr=() # initialize an array

# loop N times and append into array
for((i=1;i<=N;i++)); do
   read a && arr+=("$a")
done

关于arrays - Bash 中的数组 : Displaying all elements of array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853966/

相关文章:

linux - 如何以编程方式发送空白密码?

linux - 如何更改 docker id 和名称

javascript - 如何选择 Javascript 数组中的所有值?

python - 如何将字符串数组转换为记录数组?

python - 尝试读取 DBM 文件

C - Linux 上的一个简单的 shell - 命令的一些问题

java 轻量级调试器

bash - 如何检查文件在 BASH 条件中是否超过 1 行?

python - 在python中获取数组中具有定义值的最高索引

java - 如何创建引用其他变量的数组?