This question is different from Execute an array of string describing shell command.
For example, we have an array
myarr=( echo hello you )
How to execute it as one command, i.e. run echo hello you itself?
This question is different from Execute an array of string describing shell command.
For example, we have an array
myarr=( echo hello you )
How to execute it as one command, i.e. run echo hello you itself?
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.
myarr=( printf ' - %s\n' "first line" "second line" )
${myarr[@]}
...writes only:
-
eval Inappropriatelymyarr=( 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.
"${myarr[@]}" or it will split arguments containing spaces, tabs or newlinesevaleval, is buggy if tested with a more interesting array -- it only appears to work because the sample data is so simple little can go wrong. Try myarr=( printf ' - %s\n' "first word" "second word" ) -- if you run "${myarr[@]}" with the quotes it does the right thing (printing - first word and - second word each on a separate line). It's buggy as eval "${myarr[@]}", and also buggy as ${myarr[@]}. See the above demonstrated at ideone.com/ZVG3uqeval is passed multiple arguments it concatenates them together into a single string, then runs that string through the parser -- so quotes that were consumed in deciding where to divide up eval's arguments are completely discarded. In general, to avoid this class of bug, I always advise that only complete strings be passed to eval).