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.
Hopefully this help other's who have the same issues.
Display all contents of the array in the 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With