Sometimes you may want to output something by one program and input it into another program, but can’t use a standard pipe.
ls -l | grep ".log"
You could simply write to a temporary file:
touch tempFile.txt
ls -l > tempFile.txt
grep ".log" < tempFile.txt
This works fine for most applications, however, nobody will know what tempFile
does and someone might remove it if it contains the output of ls -l
in that directory. This is where a named pipe comes into play:
mkfifo myPipe
ls -l > myPipe
grep ".log" < myPipe
myPipe
is technically a file (everything is in Linux), so let’s do ls -l
in an empty directory that we just created a pipe in:
mkdir pipeFolder
cd pipeFolder
mkfifo myPipe
ls -l
The output is:
prw-r--r-- 1 root root 0 Jul 25 11:20 myPipe
Notice the first character in the permissions, it’s listed as a pipe, not a file.
Now let’s do something cool.
Open one terminal, and make note of the directory (or create one so that cleanup is easy), and make a pipe.
mkfifo myPipe
Now let’s put something in the pipe.
echo "Hello from the other side" > myPipe
You’ll notice this hangs, the other side of the pipe is still closed. Let’s open up the other side of the pipe and let that stuff through.
Open another terminal and go to the directory that the pipe is in (or if you know it, prepend it to the pipe):
cat < myPipe
You’ll notice that after hello from the other side
is output, the program in the first terminal finishes, as does that in the second terminal.