I want to output some data to a pipe and have the other process do something to the data line by line. Here is a toy example:
mkfifo pipe
cat pipe&
cat >pipe
Now I can enter whatever I want, and after pressing enter I immediately see the same line. But if substitute second pipe with echo
:
mkfifo pipe
cat pipe&
echo "some data" >pipe
The pipe closes after echo
and cat pipe&
finishes so that I cannot pass any more data through the pipe. Is there a way to avoid closing the pipe and the process that receives the data, so that I can pass many lines of data through the pipe from a bash script and have them processed as they arrive?
Put all the statements you want to output to the fifo in the same subshell:
# Create pipe and start reader.
mkfifo pipe
cat pipe &
# Write to pipe.
(
echo one
echo two
) >pipe
If you have some more complexity, you can open the pipe for writing:
# Create pipe and start reader.
mkfifo pipe
cat pipe &
# Open pipe for writing.
exec 3>pipe
echo one >&3
echo two >&3
# Close pipe.
exec 3>&-