【问题标题】:How to escape square brackets in expect?如何在期望中转义方括号?
【发布时间】:2020-11-24 06:38:36
【问题描述】:

在expect脚本中我无法转义方括号,示例如下,

我有一个 question.sh 脚本如下,

#!/bin/bash
echo "Would you like to specify inputs and execute the script? [Y/n]"
read $REPLY

echo "Deleted Item with ID: 50 and do cleanup? [Y/n]"
read $REPLY

echo "Deleted Item with ID: 51 and do cleanup? [Y/n]"
read $REPLY

echo "Deleted Item with ID: 52 and do cleanup? [Y/n]"
read $REPLY

对于上面的question.sh我有下面的answer.exp,用'expect answer.exp 51'命令执行同样的,

#!/usr/bin/expect -f

set timeout -1

spawn ./question.sh

set item "Deleted Item with ID: "
append item [lindex $argv 0]
append item " and do cleanup? \[Y/n\]"

expect "Would you like to specify inputs and execute the script? \[Y/n\]"
send -- "Y\r"

expect {

      $item {
            send "Y\r"
            exp_continue
      }
      " and do cleanup? \[Y/n\]" {
            send "n\r"
            exp_continue
      }
}

当我使用方括号时,期望不匹配并且不会将答案 (Y/N) 发回。

当我从问题中删除方括号并且答案脚本期望工作正常时,相同,更改后的问题和答案脚本如下。

question.sh:

 #!/bin/bash
echo "Would you like to specify inputs and execute the script? Y/n"
read $REPLY

echo "Deleted Item with ID: 50 and do cleanup? Y/n"
read $REPLY

echo "Deleted Item with ID: 51 and do cleanup? Y/n"
read $REPLY

echo "Deleted Item with ID: 52 and do cleanup? Y/n"
read $REPLY

answer.exp:

#!/usr/bin/expect -f

set timeout -1

spawn ./question.sh

set item "Deleted Item with ID: "
append item [lindex $argv 0]
append item " and do cleanup? Y/n"

expect "Would you like to specify inputs and execute the script? Y/n"
send -- "Y\r"

expect {

      $item {
            send "Y\r"
            exp_continue
      }
      " and do cleanup? Y/n" {
            send "n\r"
            exp_continue
      }
}

【问题讨论】:

标签: bash tcl expect


【解决方案1】:

expect 命令默认匹配 tcl string match style wildcard patterns,因此[Y/n] 尝试匹配字符 Y、正斜杠或 n 之一。

解决方案:

  1. 添加更多反斜杠:
append item " and do cleanup? \\\[Y/n\\\]"

所以它变成了\[Y/N\]

  1. 改用大括号:
append item { and do cleanup? \[Y/n\]}

防止反斜杠的替换。

  1. 告诉expect 在每个模式前使用-ex 选项进行精确匹配:
#!/usr/bin/expect -f

set timeout -1

spawn ./question.sh

set item "Deleted Item with ID: "
append item [lindex $argv 0]
append item " and do cleanup? \[Y/n\]"

expect -ex "Would you like to specify inputs and execute the script? \[Y/n\]"
send -- "Y\r"

expect {

      -ex $item {
            send "Y\r"
            exp_continue
      }
      -ex " and do cleanup? \[Y/n\]" {
            send "n\r"
            exp_continue
      }
}

【讨论】:

  • 也可以将2和3结合起来:expect -ex {Would you like to specify inputs and execute the script? [Y/n]}
  • 顺便说一句:AFIK 你只需要转义左括号,而不是右括号。
  • @user1934428 不会让我感到惊讶,但那样看起来很奇怪。
  • 这是因为单个右括号无论如何都没有意义。在 bash 中也是如此,您可以在其中执行 echo ] 而无需关心通配符的解释。
  • 更好的解决方案是 IMO 使用 {....} 作为字符串终止符而不是 " .... ",因为无论如何我们都不进行插值。有了这个,你不需要逃避任何事情。
猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 2011-08-17
  • 2019-08-16
  • 2011-08-10
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多