Reputation: 824
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?
Upvotes: 3
Views: 2095
Reputation: 361565
Skip the useless use of cat
and directly open fd 9:
while read -u 9 line; do //some stuff; done 9< file
If you do want to use cat
or some other arbitrary command, you wouldn't use a pipe at all. A pipe hooks stdout to stdin, but fd 9 is neither of those. Instead you'd want to open up the file descriptor first and then directly run the command that reads from it.
exec 9< <(cat file)
while read -u 9 line; do //some stuff; done
You could also combine it with the first answer if you want to do it all in one line.
while read -u 9 line; do //some stuff; done 9< <(cat file)
Upvotes: 1
Reputation: 530872
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
Upvotes: 6
Reputation: 548
Not sure why you are reading from file descriptor 9 in a pipeline like this, but can you try something like this:
cat test.in 9>&1 | while read -u 9 line; do
echo ${line}
done 9<&0
Hope this helps
Upvotes: 0