Appending elements specified in a string with quot

2019-07-17 06:31发布

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?

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条回答
Animai°情兽
2楼-- · 2019-07-17 07:17

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:

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
查看更多
登录 后发表回答