linux bash脚本获取用户输入并存储在数组中

时间:2021-09-23 02:36:21

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

我想写一个bash脚本,它将获取用户输入并将其存储在一个数组中。输入:1 4 6 9 11 17 22

I want this to be saved as array.

我希望将其保存为数组。

3 个解决方案

#1


9  

read it like this:

像这样读:

read -a arr

Test:

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

print # of elements in array:

print数组中的元素数:

echo ${#arr[@]}

OR loop through the above array

OR循环上面的数组

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

#2


1  

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.

按Ctrl-D停止输入数字。

#3


1  

Here's my 2 cents.

这是我的2美分。

#!/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


9  

read it like this:

像这样读:

read -a arr

Test:

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

print # of elements in array:

print数组中的元素数:

echo ${#arr[@]}

OR loop through the above array

OR循环上面的数组

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

#2


1  

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.

按Ctrl-D停止输入数字。

#3


1  

Here's my 2 cents.

这是我的2美分。

#!/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