bash 在bash中将多行输出捕获为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13823706/
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
Capture multiline output as array in bash
提问by djechlin
If inner.sh
is
如果inner.sh
是
#...
echo first
echo second
echo third
And outer.sh
is
并且outer.sh
是
var=`./inner.sh`
# only wants to use "first"...
How can var
be split by whitespace?
如何var
用空格分割?
回答by sampson-chen
Try this:
尝试这个:
var=($(./inner.sh))
# And then test the array with:
echo ${var[0]}
echo ${var[1]}
echo ${var[2]}
Output:
输出:
first
second
third
Explanation:
解释:
- You can make an array in bash by doing
var=(first second third)
, for example. $(./inner.sh)
runs theinner.sh
script, which prints outfirst
,second
, andthird
on separate lines. Since we don't didn't put double quotes around$(...)
, they get lumped onto the same line, but separated by spaces, so you end up with what it looks like in the previous bullet point.
- 例如,您可以通过执行 bash 在 bash 中创建数组
var=(first second third)
。 $(./inner.sh)
运行该inner.sh
脚本,它打印出来first
,second
和third
在不同的行。由于我们没有在 周围放置双引号$(...)
,因此它们会集中在同一行上,但由空格分隔,因此您最终会看到上一个要点中的样子。
回答by gniourf_gniourf
Don't forget the builtin mapfile
. It's definitely the most efficient in your case: If you want to slurp the whole file in an array, the fields of which will be the lines output by ./inner.sh
, do
不要忘记内置mapfile
. 在您的情况下,这绝对是最有效的:如果您想将整个文件放入一个数组中,其字段将是由 输出的行./inner.sh
,请执行
mapfile -t array < <(./inner.sh)
Then you'll have the first row in ${array[0]}
, etc...
然后你会有第一行${array[0]}
,等等......
For more info on this builtin and all the possible options:
有关此内置函数和所有可能选项的更多信息:
help mapfile
If you just need the first line in a variable called firstline
, do
如果您只需要名为 的变量中的第一行firstline
,请执行
read -r firstline < <(./inner.sh)
These are definitely the most efficient ways!
这些绝对是最有效的方法!
This small benchmark will prove it:
这个小基准将证明这一点:
$ time mapfile -t array < <(for i in {0..100000}; do echo "fdjsakfjds$i"; done)
real 0m1.514s
user 0m1.492s
sys 0m0.560s
$ time array=( $(for i in {0..100000}; do echo "fdjsakfjds$i"; done) )
real 0m2.045s
user 0m1.844s
sys 0m0.308s
If you only want the first word (with space delimiter) of the first line output by ./inner.sh
, the most efficient way is
如果你只想要第一行输出的第一个单词(带空格分隔符)./inner.sh
,最有效的方法是
read firstword _ < <(./inner.sh)
回答by Arnestig
You're not splitting on whitespaces but rather on newlines. Give this a whirl:
您不是在空格上拆分,而是在换行符上拆分。试一试:
IFS=$'
'
var=$(./echo.sh)
echo $var | awk '{ print }'
unset IFS