[英]Bash array variable expansion inside expect command
此问题的扩展: 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[@]}"
然后将整个命令存储在数组中
finder=( find . "${args[@]}" )
在bash中,我可以运行以下命令:
"${finder[@]}"
./some file.txt
但是当我尝试使用Expect时,出现错误
expect -c "spawn \"${finder[@]}\""
missing "
while executing
"spawn ""
couldn't read file ".": illegal operation on a directory
为什么这里不进行bash变量扩展?
expect -c COMMAND
要求COMMAND为单个参数。 它不接受多字参数,这是"${finder[@]}"
扩展为的内容。
如果您想完美地处理空白而又不打扰,那将非常棘手。 printf %q
可能有用。
双引号${finder[@]}
扩展为单独的单词:
$ printf "%s\n" expect -c "spawn \"${finder[@]}\""
expect
-c
spawn "a
b
c"
因此, expect
不是将整个命令作为单个参数。 您可以使用*
:
$ printf "%s\n" expect -c "spawn \"${finder[*]}\""
expect
-c
spawn "a b c"
${finder[*]}
将数组元素扩展为一个单词,该单词由IFS
的第一个字符分隔,默认情况下为空格。 但是, *
添加的空格与原始元素中的空格之间没有区别,因此,您不能可靠地使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.