2013-06-12 57 views
0

下面的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腳本中具有無限超時贏得這場比賽。

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 

我已經嘗試了很多東西,我不t看看如何檢查每個「給下一件事」句子之間的「現在打個招呼」句子。下面的結構不能幫助,因爲第一個問題都是類似的答案和具有每次都不同:

expect { 
    "give the next thing" {do something; exp_continue} 
    "and now say hello" {send "hello\n"} 
} 

回答

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"} 
} 
+0

你好:) 這不僅是骨頭,但解決方案:) – taalf

+0

的全身我不得不逃離「$」符號,以便把它在bash腳本。再次感謝你:) – taalf

+0

你可以這樣做'echo <<'DONE'' - 引用heredoc終結符有效地引用整個heredoc單引號,所以你不必逃避所有期望變量,這會降低可讀性。 –