bash coproc and leftover coproc output

前端 未结 3 808
自闭症患者
自闭症患者 2020-12-19 01:59

I need to read some configuration data into environment variables in a bash script.

The \"obvious\" (but incorrect) pattern is:

egrep \"pattern\" con         


        
3条回答
  •  不知归路
    2020-12-19 02:26

    What happens is, as soon as the subshell finishes, the parent shell cleans up and closes the FDs. You're lucky you even got to read the first line!

    Try this in an interactive shell:

    $ coproc ECHO { echo foo; echo bar; }
    [2] 16472
    [2]+  Done                    coproc ECHO { echo foo; echo bar; }
    $ read -u ${ECHO[0]}; echo $REPLY
    bash: read: -u: option requires an argument
    read: usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
    

    It even mops up the environment variable.

    Now try this:

    $ coproc ECHO { echo foo; echo bar; sleep 30; }
    [2] 16485
    $ read -u ${ECHO[0]}; echo $REPLY
    foo
    $ read -u ${ECHO[0]}; echo $REPLY
    bar
    $ read -u ${ECHO[0]}; echo $REPLY # blocks until the 30 seconds are up
    
    [2]+  Done                    coproc ECHO { echo foo; echo bar; sleep 30; }
    

    As for solving the problem behind the question: Yes, redirection and process substitution is the better choice for the particular example given.

提交回复
热议问题