开发者

Bash script won't re-direct input to a subprocess [duplicate]

This question already has answe开发者_如何转开发rs here: Send command to a background process (6 answers) Closed 2 years ago.

Here's a simplified example of a script I'm writing (doesn't work as is).

I want to direct STDOUT from my script to the STDIN of a subprocess.

In the example below I'm writing 'test' to STDOUT and want that to get to the subprocess which ultimately writes it to the file output.

#!/bin/bash
exec 4<&1
( cat >/tmp/output )& <&4
while true; do echo test; sleep 1; done


A (semi) standard technique for this sort of thing is:

#!/bin/sh

test -t 1 && { $0 ${1+"$@"} | cat > /tmp/output; exit; }
...

If the script is run with stdout on a tty, it is re-run with output piped to the cat.


In bash, you can use process substitution to create the subprocess and exec to redirect the script's output:

#!/bin/bash
exec > >( cat >/tmp/output )
while true; do echo test; sleep 1; done


The example is bizarre. Do you want the echo test stdout to be appended to /tmp/output? If so,

while true
do
    echo test >> /tmp/output
    sleep 1
done


The ultimate solution, thanks to @jon's pointer to coproc:

#!/bin/bash
coproc CPO { cat >/tmp/output; }
while true; do echo test >&${CPO[1]}; sleep 1; done

In reality 'echo test' is replaced with a complex sequence of monitoring and parsing of a file, and the cat subprocess is replaced with a netcat to a server and that connection is monitored with a trap on the netcat process exiting.

Thanks for all the great answers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜