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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

Try this with the user's original arguments; you'll get spawn "find . -name some file.txt".
@chepner added note about that.
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.
The actual error actually seems to be the very first quoted ", so I don't think you've addressed the problem at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.