2

这个问题的扩展: 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 -c "spawn \"${finder[@]}\""
missing "
   while executing
"spawn ""
couldn't read file ".": illegal operation on a directory

为什么这里没有发生 bash 变量扩展?

4

2 回答 2

5

expect -c COMMAND要求 COMMAND 是单个参数。它不接受多词参数,这是"${finder[@]}"扩展的。

如果你想完美地处理空白而不弄乱它会很棘手。printf %q可能有用。

于 2016-03-08T14:19:03.003 回答
0

${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,默认情况下为空格。但是,添加的空格和原始元素中的空格之间没有区别*,因此,您不能可靠地使用它。

于 2016-03-08T14:17:10.520 回答