0

I have some input element and i want to store them in array . I don't no the limit of element .

Suppose the elements are like 

one
two
three
four
five
six

The input size can be different.

i tried it like

declare -a array 

read -a array

echo ${array[@]}

but it only print first element. How can i print all values ?

I finally solve it

My code: (https://ideone.com/sy5NQh)

#!/bin/bash
# your code goes here
declare -a array
i=0
while read -r input; do
    array[$i]=$input
    ((i++))
done

echo ${array[@]}
10
  • I just test your code and works for me: xxx@rosseta:/tmp$ read -a array one true three xxx@rosseta:/tmp$ echo ${array[@]} one true three xxx@rosseta:/tmp$ echo ${array[2]} three Commented Feb 27, 2015 at 13:09
  • @d1egoaz: it print all values ?? Commented Feb 27, 2015 at 13:11
  • How are you inputting the values to read? read -a splits a single line into an array it doesn't read multiple lines. Commented Feb 27, 2015 at 13:11
  • 1
    mywiki.wooledge.org/BashFAQ/001 is probably of some use here. Commented Feb 27, 2015 at 13:12
  • 1
    Also mywiki.wooledge.org/BashFAQ/005 and in particular the mapfile hint if you have Bash 4. Commented Feb 27, 2015 at 13:26

2 Answers 2

1

Try this. It works for me

declare -a array
i=0
while read -r input; do
    array[$i]=$input
    ((i++))
done

echo ${array[@]}
Sign up to request clarification or add additional context in comments.

Comments

1

Doing it this wat will allow you to simply add the array as arguments.

#!/bin/bash

while [ "$1" != "" ]
do
        array+=("$1")
        shift
done

echo "${array[@]}"
exit

2 Comments

No need for the count just use array+=("$1") to append.
very tidy! I had forgotten about that :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.