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/