[英]Bash array variable expansion inside expect command
An extension to this question : Bash : Adding extra single quotes to strings with spaces 此问题的扩展: Bash:在带空格的字符串中添加额外的单引号
After storing the arguments of command as a bash array 将命令的参数存储为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[@]}"
Then storing whole command in an array 然后将整个命令存储在数组中
finder=( find . "${args[@]}" )
In bash I am able to run the command as below: 在bash中,我可以运行以下命令:
"${finder[@]}"
./some file.txt
But when I tried using expect, I am getting error 但是当我尝试使用Expect时,出现错误
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? 为什么这里不进行bash变量扩展?
expect -c COMMAND
requires COMMAND to be a single argument. expect -c COMMAND
要求COMMAND为单个参数。 It doesn't accept multi-word arguments, which is what "${finder[@]}"
expands to. 它不接受多字参数,这是
"${finder[@]}"
扩展为的内容。
If you want to handle whitespace perfectly without mangling it'll be tricky. 如果您想完美地处理空白而又不打扰,那将非常棘手。
printf %q
might be of use. printf %q
可能有用。
${finder[@]}
in double quotes expands into separate words: 双引号
${finder[@]}
扩展为单独的单词:
$ 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. 因此,
expect
不是将整个命令作为单个参数。 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. ${finder[*]}
将数组元素扩展为一个单词,该单词由IFS
的第一个字符分隔,默认情况下为空格。 However, there is no distinction between spaces added by *
and the whitespace in the original elements, so, you cannot reliably use this. 但是,
*
添加的空格与原始元素中的空格之间没有区别,因此,您不能可靠地使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.