bash - 如何在期望中转义方括号?

标签 bash tcl expect

在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
      }
}

最佳答案

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. 在每个模式前使用 -ex 选项告诉 expect 进行完全匹配:
#!/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
      }
}

关于bash - 如何在期望中转义方括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64981382/

相关文章:

string - TCL 字符串连接

linux - 为什么我的 git auto-update Expect 脚本不起作用?

linux - 在 ssh 进入 DC 的时钟服务器后,如何在我的脚本中触发脚本?

git - 用于 git 提交的 Shell 脚本助手

python - Linux/庆典 : Sourcing a script and then assigning it to a variable

python-tk 有未满足的依赖关系

string - 在 tcl 中连接两个字符串

expect - 如何在连接到 ssh 服务器时执行 expect 脚本

python - 预期地捕捉一个垂死的过程

regex - bash 搜索行匹配哈希并将其输出到文件