arrays - 使用其中包含空格的元素创建 Bash 数组

标签 arrays bash shell

我不明白这两个数组创建之间发生了什么,在 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/

相关文章:

r - 如何在 R 中有效地增长向量?

c# - 以这种特定方式随机排列数组?

javascript - 数组的奇怪行为 - 无法理解为什么

python - numpy 数组的累积 argmax

windows - Git Bash 看不到我的路径

Bash - 从字符串中提取数字

有时使用箭头键时 Bash 提示会发生变化

bash - 从播放列表下载 youtube 文件的 Shell 脚本

python - 提取 .rpm 文件时获取返回值

shell - UNIX 脚本 - 查找文件 - 显示日期