如何使用从另一个命令通过管道传输的输出初始化 bash 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/971162/
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
How to initialize a bash array with output piped from another command?
提问by vivekian2
Is there any way to pipe the output of a command which lists a bunch of numbers (each number in a separate line) and initialize a bash array with those numbers?
有什么方法可以通过管道输出列出一堆数字(每个数字在单独的行中)并用这些数字初始化 bash 数组的命令的输出?
Details:
This lists 3 changelist numbers which have been submitted in the following date range. The output is then piped to cut
to filter it further to get just the changelist numbers.
详细信息:这列出了在以下日期范围内提交的 3 个更改列表编号。然后将输出通过管道传输到cut
以进一步过滤以获取更改列表编号。
p4 changes -m 3 -u edk -s submitted @2009/05/01,@now | cut -d ' ' -f 2
E.g. :
例如:
422311
543210
444000
How is it possible to store this list in a bash array?
如何将此列表存储在 bash 数组中?
回答by nik
You can execute the command under ticks and set the Array like,
您可以在滴答下执行命令并设置数组,例如,
ARRAY=(`command`)
Alternatively, you can save the output of the command to a file and cat it similarly,
或者,您可以将命令的输出保存到一个文件中并以类似的方式对其进行分类,
command > file.txt
ARRAY=(`cat file.txt`)
Or, simply one of the following forms suggested in the comments below,
或者,只需以下评论中建议的以下形式之一,
ARRAY=(`< file.txt`)
ARRAY=($(<file.txt))
回答by Andrey Starodubtsev
If you use bash 4+, it has special command for this: mapfilealso known as readarray, so you can fill your array like this:
如果你使用 bash 4+,它有一个特殊的命令:mapfile也称为readarray,所以你可以像这样填充你的数组:
declare -a a
readarray -t a < <(command)
for more portable version you can use
对于更便携的版本,您可以使用
declare -a a
while read i; do
a=( "${a[@]}" "$i" )
done < <(command)
回答by Maciej Wawrzyńczuk
Quite similar to #4 but looks a bit better for me. :)
与#4 非常相似,但对我来说看起来更好一些。:)
declare -a a
readarray -t a <<< $(command)