How to execute a command represented by an array in Bash

Viewed 281
2 Answers

To work correctly in all cases, you must put quotes around your expansion.

myarr=( printf ' - %s\n' "first line" "second line" )
"${myarr[@]}"

...correctly writes as output:

 - first line
 - second line

This DOES NOT WORK if you leave out the quotes. It also does not work if you use eval.


Broken Way 1: Leaving Out Quotes

myarr=( printf ' - %s\n' "first line" "second line" )
${myarr[@]}

...writes only:

-

Broken Way 2: Using eval Inappropriately

myarr=( printf ' - %s\n' "first line" "second line" )
eval "${myarr[@]}"

...also writes only:

-

Just use [@] (turn the array into a space-separated string):

$ myarr=( echo hello you )
$ "${myarr[@]}"
hello you

Note: this works, but I would personally find it more correct to use eval:

$ eval "${myarr[@]}"
hello you

EDIT: as pointed out in the comments below, quotes are needed and the solution with eval is not correct, although it works in this case.

Related