2

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?

Community
  • 1
  • 1
anoop.babu
  • 405
  • 2
  • 6
  • 13

2 Answers2

5

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

${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.

muru
  • 4,723
  • 1
  • 34
  • 78
  • Try this with the user's original arguments; you'll get `spawn "find . -name some file.txt"`. – chepner Mar 08 '16 at 14:32
  • @chepner added note about that. – muru Mar 08 '16 at 14:38
  • 1
    Providing an answer for a question about `bash` arrays that only works if the elements of the arrays don't contain whitespace is not useful. The entire reason for arrays to exist is to handle elements that contain whitespace. – chepner Mar 08 '16 at 15:40
  • The actual error actually seems to be the very first quoted `"`, so I don't think you've addressed the problem at all. – chepner Mar 08 '16 at 16:37