bash 将 for 循环的输出存储到数组或变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41860171/
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
Store output of for loop into an array or variable
提问by zozo6015
I have a for loop as shown below. I need the whole output of the loop added into an array or variable.
我有一个 for 循环,如下所示。我需要将循环的整个输出添加到数组或变量中。
for i in $ip
do
curl -s $i:9200
done
Any idea how I can achieve that?
知道我如何实现这一目标吗?
回答by anubhava
You can use it like this:
你可以这样使用它:
# declare an array
declare -a arr=()
for i in $ip
do
# append each curl output into our array
arr+=( "$(curl -s $i:9200)" )
done
# check array content
declare -p arr
It is important to use quotes around curl comment to avoid splitting words of curl
command's output into multiple array entries. With quotes all of the curl output will become a single entry in the array.
在 curl 注释周围使用引号很重要,以避免将curl
命令输出的单词拆分为多个数组条目。使用引号,所有 curl 输出将成为数组中的单个条目。
回答by Richard Hamilton
You can use +=
您可以使用 +=
declare -a output
for i in $ip
do
output+=("$(curl -s $i:9200)")
done
回答by John Bollinger
You can capture the output of any command, including a compound command, by enclosing it in $()
. Using that technique, you can capture the output of your for
loop in a variable like so:
您可以捕获任何命令的输出,包括复合命令,将其包含在$()
. 使用该技术,您可以for
在变量中捕获循环的输出,如下所示:
results=$(
for i in $ip
do
curl -s $i:9200
done
)
In principle, capturing into an array can be done in similar fashion, but handling element delimiters appropriately could prove difficult.
原则上,可以以类似的方式捕获到数组中,但适当地处理元素分隔符可能会被证明是困难的。