Linux bash script get user input and save in array

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

I want this to be saved as an array.

+4
source share
3 answers

read it as follows:

read -a arr 

Test:

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

print the number of elements in the array:

 echo ${#arr[@]} 

OR loop through the specified array

 for i in ${arr[@]} do echo $i # or do whatever with individual element of the array done 
+8
source

How about this:

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

Press Ctrl-D to stop entering numbers.

+1
source

Here are 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 
+1
source

Source: https://habr.com/ru/post/1487124/


All Articles