How to use 'coproc' to interact with another command driven program

前端 未结 1 1957
终归单人心
终归单人心 2021-02-06 07:53

Ok, obviously I am NOT a bash guru and am in need of one!

I have never used \'coproc\' before, but it seems to be just what I need. But, I have to admit that I can not

相关标签:
1条回答
  • 2021-02-06 08:15
    result = $(echo 'command' <&${bkgndProc[0]})    ### Doesn't work for me
    

    wouldn't work at least basically since you have spaces on it

    result=$(echo 'command' <&${bkgndProc[0]})
    

    ---- Update ----

    A simple concept could be shown in a script like this:

    #!/bin/bash
    
    # create the co-process
    coproc myproc {
        bash
    }
    
    # send a command to it (echo a)
    echo 'echo a' >&"${myproc[1]}"
    
    # read a line from its output
    read line <&"${myproc[0]}"
    
    # show the line
    echo "$line"
    

    Outputs:

    a
    

    Another which reads multiple lines using a timeout:

    #!/bin/bash
    
    coproc myproc {
        bash
    }
    
    # send a command to message 4 random numbers in 4 lines
    echo 'echo "$RANDOM"; echo "$RANDOM"; echo "$RANDOM"; echo "$RANDOM"' >&"${myproc[1]}"
    
    # keep reading the line until it times out
    while read -t 1 -u "${myproc[0]}" line; do
        echo "$line"
    done
    

    Output:

    17393
    1423
    8368
    1782
    

    If we use cat, it would no longer quit since the other end is still alive and connected, and EOF is not yet reached. It's the reason why we used timeouts.

    cat <&"${myproc[0]}"
    
    0 讨论(0)
提交回复
热议问题