简体   繁体   English

Bash 中的数组:显示数组的所有元素

[英]Array in Bash: Displaying all elements of array

 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   

Tried all the ways to display all the elements of the array but not getting the desired output.尝试了所有方法来显示数组的所有元素,但没有获得所需的输出。 It's displaying the last element of the array.它显示数组的最后一个元素。

To be able to populate an array in loop use: 为了能够循环填充数组,请使用:

arr+=("$var")

Full code: 完整代码:

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

您正在读取数组arr的数据并尝试打印array

You keep redefining array with read -a . 您继续使用read -a重新定义array The code should be written like this instead: 该代码应该这样写:

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

There are probably better ways to doing this. 可能有更好的方法可以做到这一点。 I just wanted to show how to fix your current code. 我只是想展示如何修复您的当前代码。

Example run 运行示例

$ bash ./dummy.sh 
Enter N 
2
3
4
3 4
3 4

Hopefully this help other's who have the same issues.希望这可以帮助其他有同样问题的人。

Display all contents of the array in the shell:在 shell 中显示数组的所有内容:

"${arr[*]}"

Cleaning up your script (not sure what your intention was, though):清理你的脚本(但不确定你的意图是什么):

read -p "Enter N " N # User inputs the number of entries for the array
  ARR=() # Define empty array
  #using c-style loop
  for ((i=1;i<=N;i++))
  do
    read -p "Enter array element number $N: " ADD # Prompt user to add element
    ARR+=($ADD) # Actually add the new element to the array.
  done
echo "${ARR[*]}" # Display all array contents in a line.

I found a similar solution from @choroba at: How to echo all values from array in bash我从@choroba 找到了一个类似的解决方案: How to echo all values from array in bash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM