简体   繁体   中英

Bash array variable expansion inside expect command

An extension to this question : Bash : Adding extra single quotes to strings with spaces

After storing the arguments of command as a bash array

touch "some file.txt"
file="some file.txt"
# Create an array with two elements; the second element contains whitespace
args=( -name "$file" )
# Expand the array to two separate words; the second word contains whitespace.
find . "${args[@]}"

Then storing whole command in an array

finder=( find . "${args[@]}" )

In bash I am able to run the command as below:

"${finder[@]}"
./some file.txt

But when I tried using expect, I am getting error

expect -c "spawn \"${finder[@]}\""
missing "
   while executing
"spawn ""
couldn't read file ".": illegal operation on a directory

Why is bash variable expansion not happening here?

expect -c COMMAND requires COMMAND to be a single argument. It doesn't accept multi-word arguments, which is what "${finder[@]}" expands to.

If you want to handle whitespace perfectly without mangling it'll be tricky. printf %q might be of use.

${finder[@]} in double quotes expands into separate words:

$ printf "%s\n" expect -c "spawn \"${finder[@]}\""
expect
-c
spawn "a
b
c"

So, expect is not getting the entire command as a single argument. You could use * :

$ printf "%s\n" expect -c "spawn \"${finder[*]}\""
expect
-c
spawn "a b c"

${finder[*]} expands the array elements into a single word separated by the first character of IFS , which is space by default. However, there is no distinction between spaces added by * and the whitespace in the original elements, so, you cannot reliably use this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM