1

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
David Parks
  • 30,789
  • 47
  • 185
  • 328
  • I'm not sure to understand what you expect your script to do. You want the output of `echo test` to be directed to the STDIN of another process, don't you? – jopasserat Jul 06 '11 at 11:13
  • Yep, that's what I am trying to do, and coproc was a perfect solution. The underlying issue that I abstracted out of this question is that the coprocess in this case is netcat and I specifically need to run it as a subprocess so that I can monitor when it exits (when the socket connection fails due to network error or server restart) and restart the connection or set a flag to buffer output until the connection can be reestablished. – David Parks Jul 06 '11 at 15:27

4 Answers4

2

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.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

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
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • Interesting, thanks for that, I had played with this approach but couldn't work out the syntax and thought I was just off base in the attempt. – David Parks Jul 06 '11 at 15:33
0

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
l0b0
  • 55,365
  • 30
  • 138
  • 223
  • Perhaps a little oversimplified. The echo test essentially replaces a large section of code that monitors a status file for changes, parses it, and ultimately needs to write some results to a socket using netcat (or write to a buffer file if the netcat process isn't able to connect to the server, or if it looses that connection). – David Parks Jul 06 '11 at 15:05
0

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!

David Parks
  • 30,789
  • 47
  • 185
  • 328