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?
CodePudding user response:
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:
-
CodePudding user response:
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.