Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe stdout to another process's file descriptor

Tags:

bash

This one is foiling me so far. I know how to redirect my stdout to another file descriptor in the same process. I know how to pipe stdout to another process's stdin. But what if I want to pipe a process's stdout to a file descriptor in another process?? Specifically, for the case of while read...

  cat file | while read -u 9 line; do //some stuff; done

How do I get cat's output onto file descriptor 9 of the while loop?

like image 824
Roguebantha Avatar asked Jan 19 '26 03:01

Roguebantha


1 Answers

Pipes work specifically with standard input and output (file descriptors 0 and 1); they don't generalize to other descriptors. Use process substitution and input redirection instead.

while read -u 9 line; do
  ...
done 9< <(cat file)

Of course, you shouldn't use cat like this; just use regular input redirection

while read -u 9 line; do
  ...
done 9< file

Bonus, POSIX-compliant answer: use a named pipe.

mkfifo p
cat file > p &
while read line <&9; do
  ...
done 9< p
like image 178
chepner Avatar answered Jan 21 '26 08:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!