代码之家  ›  专栏  ›  技术社区  ›  keypoint

shell动态响应终端提示

  •  1
  • keypoint  · 技术社区  · 6 年前

    问题。上海

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

    响应者。上海

    #!/usr/bin/expect -f
    
    set timeout -1
    
    spawn ./questions.sh
    
    while true {
    
        expect {
            "*dog*" { send -- "bark\r" }
    
            "^((?!dog).)*$" { send -- "mew\r" }
        }
    
    
    }
    
    expect eof
    

    正在运行:'/响应者。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 ?
    

    尝试并搜索了多种方法,但仍然不起作用。非常感谢你。

    1 回复  |  直到 6 年前
        1
  •  3
  •   glenn jackman    6 年前

    expect程序挂起,因为您匹配第一条“狗”,发送吠声,然后您 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”要么是“not dog”,后跟空格、问号和行尾字符。

    这个 exp\u继续 命令将保持代码在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
    }