以下bash脚本是一款游戏。它多次问同一个问题give the next thing
。
首先是apple
,第二个是cheese
,第三个是bread
,第四个是bacon
。
在随机数量的问题之后,它要求说hello
。
示例:
give the next thing
apple
give the next thing
cheese
and now say hello
hello
bravo !
或:
give the next thing
apple
and now say hello
cheese
you failed!
目标是在bash脚本中使用 expect 赢得此游戏,在中使用无限超时。
game.sh
脚本:
#!/bin/bash
min=1;max=4;imax=0
while [ "$imax" -lt "$min" ]; do imax=$RANDOM; let "imax %= $((max+1))"; done
i=1
for thing in apple cheese bread bacon; do
echo "give the next thing"; read ans
if [ ! "$ans" == "$thing" ]; then echo "you failed!"; exit 1; fi
let "i += 1"
if [ "$i" -gt "$imax" ]; then break; fi
done
echo "and now say hello"; read ans
if [ ! "$ans" == "hello" ]; then echo "you failed!"; exit 1; fi
echo "bravo !"
exit 0
期望脚本基础,只有在问题数量正好为4时才能赢得游戏:
#!/bin/bash
expect << DONE
spawn sh game.sh
set timeout -1
expect "give the next number"
send "apple\n"
expect "give the next number"
send "cheese\n"
expect "give the next number"
send "bread\n"
expect "give the next number"
send "bacon\n"
expect "and now say hello"
send "hello\n"
DONE
exit 0
我尝试了很多东西,但是我没有看到如何检查每个“给下一件事”句子之间的“现在打个招呼”句子。以下结构无法帮助,因为第一个问题都是相似的,每次答案都必须不同:
expect {
"give the next thing" {do something; exp_continue}
"and now say hello" {send "hello\n"}
}
答案 0 :(得分:1)
答案的骨头将是:
proc do_something {n} {
# do something given the counter value $n
return [lindex {apple cheese bread bacon} $n]
}
set count 0
expect {
"give the next thing" {
send "[do_something $count]\r"
incr count
exp_continue
}
"and now say hello" {send "hello\r"}
}