#!/bin/bash
declare -a animals=("dog" "cat")
declare -a num=("1" "2" "3")
for a in "${animals[@]}"
do
for n in "${num[@]}"
do
echo "$n $a ?"
read REPLY
echo "Your answer is: $REPLY"
done
done
#!/usr/bin/expect -f
set timeout -1
spawn ./questions.sh
while true {
expect {
"*dog*" { send -- "bark\r" }
"^((?!dog).)*$" { send -- "mew\r" }
}
}
expect eof
1 dog ?
bark
Your answer is: bark
2 dog ?
bark
Your answer is: bark
3 dog ?
bark
Your answer is: bark
1 cat ?
mew
Your answer is: mew
2 cat ?
mew
Your answer is: mew
3 cat ?
mew
Your answer is: mew
1 dog ?
bark
Your answer is: bark
2 dog ?
bark
Your answer is: bark
3 dog ?
bark
Your answer is: bark
1 cat ?
尝试并搜索多种方式,但仍无法正常工作。非常感谢你。
答案 0 :(得分:3)
期望程序挂起,因为你匹配第一个" dog",发送bark,然后你expect eof
无限超时。当然,你没有" eof"因为shell脚本正在等待输入。
您需要对循环使用exp_continue
命令,而不是while
:
#!/usr/bin/expect -f
set timeout -1
spawn ./questions.sh
expect {
-re {dog \?\r\n$} { send -- "bark\r"; exp_continue }
-re {(?!dog)\S+ \?\r\n$} { send -- "mew\r"; exp_continue }
eof
}
我使模式更加具体:" dog"或者"不是狗"其次是空格,问号和行尾字符。
exp_continue
命令将使代码在expect命令中循环,直到" eof"遇到了。
我们可以使模式有点干燥:
expect {
-re {(\S+) \?\r\n$} {
if {$expect_out(1,string) eq "dog"} then {send "bark\r"} else {send "mew\r"}
exp_continue
}
eof
}