Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to write a bash script that will get user input and store it in an array. Input: 1 4 6 9 11 17 22

I want this to be saved as array.

share|improve this question
1  
you don't neeed an array to loop over the values. –  Karoly Horvath Jun 19 '13 at 19:31
    
I Dont want to run a dynamic loop. the input will be used in further loops in the code. –  Vignesh Jun 19 '13 at 19:35
    
as long as you don't need random access (indexing), there's no reason to use arrays. –  Karoly Horvath Jun 19 '13 at 19:36
    
how can i just save it in an array? –  Vignesh Jun 19 '13 at 19:37
add comment

2 Answers

up vote 3 down vote accepted

read it like this:

read -a arr

Test:

read -a arr <<< "1 4 6 9 11 17 22"

print # of elements in array:

echo ${#arr[@]}

OR loop through the above array

for i in ${arr[@]}
do
   echo $i # or do whatever with individual element of the array
done
share|improve this answer
    
@anubhava: can u explain why there is an @? Now i get the unexpected token error. I think the for brackets are not balanced –  Vignesh Jun 19 '13 at 19:53
    
can you try quotes: for i in "${arr[@]}" –  anubhava Jun 19 '13 at 19:59
    
@anubhava: That gives me the same error. Tried the quotes –  Vignesh Jun 19 '13 at 20:03
    
let us continue this discussion in chat –  anubhava Jun 19 '13 at 20:03
add comment

How about this:

while read line
do
    my_array=("${my_array[@]}" $line)
done
printf -- 'data%s ' "${my_array[@]}"

Hit Ctrl-D to stop entering numbers.

share|improve this answer
1  
my_array+=( $line ) would be much simpler. –  chepner Jun 19 '13 at 19:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.