Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 617
Manoj Kumar Avatar asked Aug 15 '26 15:08

Manoj Kumar


2 Answers

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

like image 137
Juno Sprite Avatar answered Aug 17 '26 05:08

Juno Sprite


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
like image 40
anubhava Avatar answered Aug 17 '26 06:08

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!