Manoj Kumar
Manoj Kumar

Reputation: 29

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.

Upvotes: 2

Views: 10967

Answers (4)

Juno Sprite
Juno Sprite

Reputation: 645

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

Upvotes: 6

Dathan
Dathan

Reputation: 4553

you are reading the data in an array arr and trying to print array

Upvotes: 2

anubhava
anubhava

Reputation: 785631

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

Upvotes: 2

Stefan Becker
Stefan Becker

Reputation: 5962

You keep redefining array with read -a. 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

Upvotes: 1

Related Questions