外壳动态回答终端提示 [英] shell dynamically answer to terminal prompt

查看:136
本文介绍了外壳动态回答终端提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

运行:"./responder.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

实际结果:挂在猫"问题上,没有回应...

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

尝试并搜索了多种方法,但仍然无法正常工作.非常感谢.

tried and searched multiple ways but still not working. thank you very much.

推荐答案

由于您匹配第一个狗",发送树皮,然后您expect eof并具有无限超时,所以期望程序挂起.当然,您没有"eof",因为shell脚本正在等待输入.

The expect program hangs because you match the first "dog", send bark, then you expect eof with an infinite timeout. Of course you don't have "eof" because the shell script is waiting for input.

您需要对循环使用exp_continue命令,而不是while:

You need to use the exp_continue command for your loops, not 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
}

我使模式更加具体:狗"或非狗",后跟空格,问号和行尾字符.

I made the patterns much more specific: either "dog" or "not dog" followed by a space, question mark and end-of-line characters.

exp_continue命令将使代码循环在Expect命令内,直到遇到"eof"为止.

The exp_continue commands will keep the code looping within the expect command until "eof" is encountered.

我们可以将图案变干一点:

We can make the pattern a little DRYer:

expect {
    -re {(\S+) \?\r\n$} { 
        if {$expect_out(1,string) eq "dog"} then {send "bark\r"} else {send "mew\r"} 
        exp_continue 
    }
    eof
}

这篇关于外壳动态回答终端提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆