使用命令输出中带引号的条目在Bash中创建数组 [英] Creating an Array in Bash with Quoted Entries from Command Output
问题描述
我无法从标准输出中形成bash数组.我将其简化为以下最小示例:
I'm having trouble forming a bash array from a standard output. I've boiled it down to this minimal example:
~$ a=($(echo '1 2 3 "foo bar"'))
~$ echo ${a[0]}
1
~$ echo ${a[1]}
2
~$ echo ${a[2]}
3
~$ echo ${a[3]}
"foo
~$ echo ${a[4]}
bar"
我相信正在发生的事情是"foo
和bar"
在标准输出中被视为单独的项目,但目标是将这些项目合并为一个数组.
I believe what is happening is that "foo
and bar"
are considered separate items in the standard output, but the goal would be to consolidate those items into one for the array.
很明显,我可以编写一个小循环将这些术语合并为一个,但是我想知道是否有更优雅的解决方案?
Obviously, I could write a small loop to consolidate these terms into one, but I'm wondering of there is a more elegant solution?
编辑:在我的代码中代替echo '1 2 3 "foo bar"'
的内容相当复杂,但要点是我需要从这种形式的一些未知标准输出中形成一个数组.
EDIT: What goes in place of echo '1 2 3 "foo bar"'
in my code is fairly convoluted, but the point is that I need to form an array from some unknown standard output of this form.
推荐答案
xargs
能够识别引号
mapfile -t a <<<"$(echo '1 2 3 "foo bar"' | xargs -n 1)"
printf "%s\n" "${a[@]}"
1
2
3
foo bar
这篇关于使用命令输出中带引号的条目在Bash中创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!