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.