11

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.

4
  • 1
    you don't neeed an array to loop over the values. Commented Jun 19, 2013 at 19:31
  • I Dont want to run a dynamic loop. the input will be used in further loops in the code. Commented Jun 19, 2013 at 19:35
  • as long as you don't need random access (indexing), there's no reason to use arrays. Commented Jun 19, 2013 at 19:36
  • how can i just save it in an array? Commented Jun 19, 2013 at 19:37

3 Answers 3

14

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
Sign up to request clarification or add additional context in comments.

3 Comments

@anubhava: can u explain why there is an @? Now i get the unexpected token error. I think the for brackets are not balanced
can you try quotes: for i in "${arr[@]}"
4

Here's my 2 cents.

#!/bin/sh

read -p "Enter server names separated by 'space' : " input

for i in ${input[@]}
do
   echo ""
   echo "User entered value :"$i    # or do whatever with individual element of the array
   echo ""
done

Comments

2

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.

1 Comment

my_array+=( $line ) would be much simpler.

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.