linux bash script get user input and store in a ar

2019-04-29 18:22发布

问题:

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.

回答1:

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


回答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.



回答3:

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


标签: linux bash shell