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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17199736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:15:41  来源:igfitidea点击:

linux bash script get user input and store in a array

linuxbashshell

提问by Vignesh

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.

我希望将其保存为数组。

采纳答案by anubhava

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

OR 循环遍历上述数组

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

回答by jh314

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 停止输入数字。

回答by vardhan

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