将带引号的字符串中指定的元素附加到bash数组中

时间:2022-07-22 16:48:55

I am trying to append an item to an array that is stored in a variable, however it's not acting entirely how I'd expect it to.

我试图将一个项附加到一个存储在变量中的数组中,但是它并没有完全按照我的期望执行。

Here is what I'm trying to do:

这就是我想做的:

array=()

item_to_add="1 '2 3'"

array+=(${item_to_add})

for item in "${array[@]}"; do
    echo "item: ${item}"
done

I'd expect this to output the following:

我期望这个输出如下:

item: 1
item: '2 3'

However I get the following output instead:

但是我得到的输出是:

item: 1
item: '2
item: 3'

Is there any way to make it act like this code without using something like eval?

有没有什么方法可以让它像这样的代码,而不用eval之类的东西呢?

array=()

array+=(1 '2 3')

for item in "${array[@]}"; do
    echo "item: ${item}"
done

And the output from it:

以及它的输出:

item: 1
item: '2 3'

1 个解决方案

#1


5  

xargs parses quotes in its input. This is usually a (specification-level) bug rather than a feature (it makes filenames with literal quotations nearly impossible to work with without non-POSIX extensions such as -d or -0 overriding the behavior), but in present circumstances it comes in quite handy:

xargs解析输入中的引号。这通常是一个(特定级别的)bug,而不是一个特性(如果没有-d或-0之类的非posix扩展,几乎不可能使用带有文字引语的文件名来重写行为),但在目前情况下,它非常方便:

array=()

item_to_add="1 '2 3'"

while IFS= read -r -d '' item; do # read NUL-delimited stream
  array+=( "$item" )              # and add each piece to an array
done < <(xargs printf '%s\0' <<<"$item_to_add") # transform string to NUL-delimited stream

printf 'item: %s\n' "${array[@]}"

...emits...

发出…

item: 1
item: 2 3

#1


5  

xargs parses quotes in its input. This is usually a (specification-level) bug rather than a feature (it makes filenames with literal quotations nearly impossible to work with without non-POSIX extensions such as -d or -0 overriding the behavior), but in present circumstances it comes in quite handy:

xargs解析输入中的引号。这通常是一个(特定级别的)bug,而不是一个特性(如果没有-d或-0之类的非posix扩展,几乎不可能使用带有文字引语的文件名来重写行为),但在目前情况下,它非常方便:

array=()

item_to_add="1 '2 3'"

while IFS= read -r -d '' item; do # read NUL-delimited stream
  array+=( "$item" )              # and add each piece to an array
done < <(xargs printf '%s\0' <<<"$item_to_add") # transform string to NUL-delimited stream

printf 'item: %s\n' "${array[@]}"

...emits...

发出…

item: 1
item: 2 3