m-ric m-ric - 26 days ago 5
Linux Question

make bash printf consider array as one argument

On ubuntu-14.04, bash-4.3.11, I run this:

$ _array=(1 2 3)
$ echo "${_array[@]} bloup"
1 2 3 bloup
$ printf "%s bloup\n" "${_array[@]}"
1 bloup
2 bloup
3 bloup

  • How can I make printf behave as echo in this situation?

  • Why does printf consider the double-quoted array as three arguments? i.e. what expansion mechanism am I missing here?

As a workaround, I use this:

$ _string=${_array[@]}
$ printf "%s bloup\n" "$_string"
1 2 3 bloup


Just use * in place of @:

printf "%s bloup\n" "${_array[*]}"

The purpose of @ is to make treat the expansion as separate quoted words for each element, so that the expansion of an array like ("a b" c d) is treated as 3 arguments, not 4.