Jack Wilsdon Jack Wilsdon - 4 months ago 7
Bash Question

Appending elements specified in a string with quotes to a bash array

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'

Answer

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