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 
2
  • 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? Commented Jul 6, 2011 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. Commented Jul 6, 2011 at 15:27

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

1 Comment

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.
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 

1 Comment

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).
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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.