我无法在期望脚本中转义方括号,示例如下,
我有一个 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
Run Code Online (Sandbox Code Playgroud)
对于上面的问题.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
}
}
Run Code Online (Sandbox Code Playgroud)
当我涉及方括号时,期望不匹配并且不会发回答案(Y/N)。
当我从问题中删除方括号并且答案脚本期望工作正常时,更改后的问题和答案脚本如下所示。
问题.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
Run Code Online (Sandbox Code Playgroud)
答案.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
}
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,该命令与 tcl样式通配符模式expect匹配,因此尝试匹配字符 Y、正斜杠或 n 之一。string match[Y/n]
解决方案:
append item " and do cleanup? \\\[Y/n\\\]"
Run Code Online (Sandbox Code Playgroud)
所以它变成了\[Y/N\].
append item { and do cleanup? \[Y/n\]}
Run Code Online (Sandbox Code Playgroud)
以防止反斜杠的替换。
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
}
}
Run Code Online (Sandbox Code Playgroud)