简体   繁体   English

如何使用另一个命令输出管道来初始化bash数组?

[英]How to initialize a bash array with output piped from another command?

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. 详细信息:此列表列出了在以下日期范围内提交的3个更改列表编号。 The output is then piped to cut to filter it further to get just the changelist numbers. 然后输出管道进行cut以进一步过滤以获得更改列表编号。

p4 changes -m 3 -u edk -s submitted @2009/05/01,@now | cut -d ' ' -f 2

Eg : 例如:

422311
543210
444000

How is it possible to store this list in a bash array? 如何将此列表存储在bash数组中?

You can execute the command under ticks and set the Array like, 您可以在ticks下执行命令并将Array设置为,

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))

If you use bash 4+, it has special command for this: mapfile also 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)

Quite similar to #4 but looks a bit better for me. 与#4非常相似,但对我来说看起来更好一些。 :) :)

declare -a a
readarray -t a <<< $(command)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM