bash coproc and leftover coproc output

独自空忆成欢 提交于 2019-11-29 09:48:46

As per comments above, you can use process substitution to achieve just that. This way, read is not run in a subshell and the captured vars will be available within the current shell.

read VAR1 VAR2 VAR3 < <(egrep "pattern" config-file.cfg)

"If the <(list) form is used, the file passed as an argument should be read to obtain the output of list" -- what "file passed as an agrument" are they talking about?

That is rather cryptic to me too. The chapter on process substitution in Advanced Bash-scripting Guide has a more comprehensive explanation.

The way I see it, when the <(cmd) syntax is used, the ouput of cmd is made available via a named pipe (or temp file) and the syntax is replaced by the filename of the pipe/file. So for the example above, it would end up being equivalent to:

read VAR1 VAR2 VAR3 < /dev/fd/63

where /dev/fd/63 is the named pipe connected to the stdout of cmd.

If I understand correctly your question (and I hope I'm not stating the obvious), read reads one line at a time, as in:

$ read a b c < config-file.cfg && echo $?
0

or:

$ printf '%s\n%s\n' one two | { read; echo "$REPLY";}
one

$ echo ${PIPESTATUS[@]}
0 0

To read all the input you'll need a loop:

$ coproc cat config-file.cfg
[1] 3460

$ while read -u ${COPROC[0]} VAR1 VAR2 VAR3; do echo $VAR1 $VAR2 $VAR3; done
LINE1 A1 B1 C1
LINE2 A2 B2 C2
LINE3 A3 B3 C3
[1]+  Done                    coproc COPROC cat config-file.cfg

Just to add that this is explained in the FAQ.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!