shell动态回答终端提示

时间:2018-05-10 18:09:41

标签: regex command-line expect

questions.sh

#!/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

responder.sh

#!/usr/bin/expect -f

set timeout -1

spawn ./questions.sh

while true {

    expect {
        "*dog*" { send -- "bark\r" }

        "^((?!dog).)*$" { send -- "mew\r" }
    }


}

expect eof

正在运行:'。/ response.sh'

预期结果:

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

实际结果:挂在'cat'问题但没有回复......

1 dog ?
bark
Your answer is: bark
2 dog ?
bark
Your answer is: bark
3 dog ?
bark
Your answer is: bark
1 cat ?

尝试并搜索多种方式,但仍无法正常工作。非常感谢你。

1 个答案:

答案 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
}