gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:55:13 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com