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 脚本中使用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"}
}
4

1 回答 1

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"}
}
于 2013-06-12T18:26:09.040 回答