我不明白这两个数组创建之间发生了什么,在 cygwin GNU bash 上测试
$ array=('hello world' how are you)
$ echo $array
'hello world' <----- This is expected
编辑:正如 chepner 指出的那样,输出是
hello world <----- no ''
现在将变量赋值作为中间步骤
$ words="'hello world' how are you"
$ echo $words
'hello world' how are you
$ array=($words)
$ echo $array
'hello <----- Why was it split with ' '?
最佳答案
codeforester's helpful answer很好地解释了这个问题。
至于解决方案:
注意:如果您正在处理的输入实际上没有嵌入 引号来划分元素,只需使用 readarray -t array < <(...)
原样,其中 ( ...
) 表示产生输出的命令,其行 应作为数组的单个元素捕获强>.
xargs
通常理解文字输入中的 shell 引用(转义、嵌入 引号除外):
words="'hello world' how are you"
echo "$words" | xargs -n 1 printf '%s\n'
hello world
how
are
you
注意如何 hello world
被认为是一个单个 参数,以及它如何包含 '
实例被移除。
在 bash
中创建数组时利用它(由于 readarray
假设 Bash 4.x,但有可能使其在 Bash 3.x[1] 中工作
):
words="'hello world' how are you"
readarray -t array < <(xargs -n 1 printf '%s\n' <<<"$words")
declare -p array
产生:
declare -a array=([0]="hello world" [1]="how" [2]="are" [3]="you")
(封闭的 "
实例是 declare -p
输出格式的产物 - 它们具有语法功能,如果您要将输出重用为 shell 源代码.)
[1] Bash v3+ 解决方案,使用 read
而不是 readarray
:
words="'hello world' how are you"
IFS=$'\n' read -d '' -ra array < <(xargs -n 1 printf '%s\n' <<<"$words")
declare -p array
关于arrays - 使用其中包含空格的元素创建 Bash 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315574/