首页 > 解决方案 > Bash:通过管道进行进程的相互交互

问题描述

环境: Linux/Docker,bash 4.2 版。

问题:

我尝试了多种设置coproc。但是,我要么陷入停滞状态,要么没有收到数据。如何实现如下所示的设置bash

                       .------>------------------------.
     .---------.       |         .------------.  stdin |       .-----------.
     | user    |-------'         | server-app |<-------+-------| client.sh |
     | console |<--+-------------|            |     .--------->|           |
     '---------'   |      stdout '------------'     |          '-----------'
                   '--------------------------------'

我的尝试:

coproc server.app

function expect { local expectation=$1
        # read from pipe until $expectation occurs in the input stream
        # when found, echo the line to 'stdout'
        echo "EXPECT: '$expectation'"
        while true; do
            read text <&"${COPROC[0]}"
            if [[ "$text" == *"$expectation"* ]]; then
                    echo $text 
                    break
            fi
        done
}

function send { local command=$1
        # send $command through pipe 
        echo "SEND: $command"
        echo "$command" >&"${COPROC[1]}"

}


expect "Conected to URL" 
send   "open"
expect "Session keepalive"
send   "session open"

# use the reported session identifier to setup the user command
session_n=$(expect "Identifier of Session created" | cut -d' ' -f5)    
command=$(echo "$user_command" | sed -e "s/SESSION/$session_n/g")

最后三行仅演示了对server-app' 输出的可能处理。这又有什么问题呢?怎么可能带去上班。

标签: bashpipecoproc

解决方案


正如@sexpect 所提到的,“自然”的方式是解决问题的期望。该工具将基于 Tcl 的脚本作为输入。

 spawn server-app

将开始在server-app期望的控制之下。expect也是这些脚本中的关键字。

 expect -re "something (..)"

等待与表达式匹配的输出something (..)

 send ...

向应用程序发送一些字符。

expect_tty ...

从启动期望脚本的用户那里获取一些输入。


推荐阅读