【问题标题】:Bash array variable expansion inside expect command期望命令内的Bash数组变量扩展
【发布时间】:2016-03-08 13:50:51
【问题描述】:

这个问题的扩展: Bash : Adding extra single quotes to strings with spaces

将 command 的参数存储为 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 变量扩展?

【问题讨论】:

    标签: bash expect variable-expansion


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      双引号中的${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 的第一个字符分隔,默认为空格。但是,* 添加的空格与原始元素中的空格没有区别,因此您不能可靠地使用它。

      【讨论】:

      • 用用户的原始参数试试这个;你会得到spawn "find . -name some file.txt"
      • @chepner 对此添加了注释。
      • 提供关于bash 数组的问题的答案仅在数组元素不包含空格时才有效,这是没有用的。数组存在的全部原因是为了处理包含空格的元素。
      • 实际的错误实际上似乎是第一个引用的",所以我认为你根本没有解决这个问题。
      猜你喜欢
      • 2014-01-28
      • 1970-01-01
      • 2013-09-29
      • 2021-04-25
      • 1970-01-01
      • 2018-08-22
      相关资源
      最近更新 更多