在expect命令中使用Bash数组变量扩展

ano*_*abu 2 bash expect variable-expansion

这个问题的扩展: Bash:为带空格的字符串添加额外的单引号

将命令参数存储为bash数组后

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[@]}"
Run Code Online (Sandbox Code Playgroud)

然后将整个命令存储在一个数组中

finder=( find . "${args[@]}" )
Run Code Online (Sandbox Code Playgroud)

在bash中我可以运行如下命令:

"${finder[@]}"
./some file.txt
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用expect时,我收到了错误

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

为什么bash变量扩展不会发生在这里?

Joh*_*ica 5

expect -c COMMAND要求COMMAND成为单个参数.它不接受多字参数,这是"${finder[@]}"扩展的内容.

如果你想完美地处理空白而不破坏它将会很棘手.printf %q可能有用.