Course contentsShow
← Linux
Lesson 142 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Named Pipe Communication

Create IPC channels between scripts using filesystem-backed FIFO queues.

In this lesson, you will learn how to enable two independent Bash scripts to talk to each other in real-time using a special file called a "Named Pipe" (or FIFO).

What is a Named Pipe?

Usually, when you pipe data between commands (e.g., ls | grep .txt), the connection exists only while the commands are running. A Named Pipe, however, is a special file that exists on your hard drive. Because it lives in the filesystem, any process that knows the file path can read from or write to it, even if they aren't part of the same pipeline. It acts as a mailbox: one script puts data in, and another script takes it out.

Creating and Using a FIFO

To create a named pipe, we use the mkfifo command. Think of this as creating a "gateway" file.

Step 1: Create the pipe

mkfifo my_pipe

Step 2: The Receiver (Reader) Open a terminal and tell a script to listen to the pipe. It will "hang" here until data arrives:

cat < my_pipe

Step 3: The Sender (Writer) Open a different terminal and send a message into that same file:

echo "Hello from the other script!" > my_pipe

Why use this?

Named pipes are incredibly powerful for Inter-Process Communication (IPC). Unlike standard temporary files, data sent through a FIFO is transient. As soon as the reader consumes the data, the pipe is effectively empty again, meaning you don't have to worry about cleaning up large log files or handling disk space.

Because we’ve already covered Stream Redirection and Signal Propagation, you can combine these techniques to build sophisticated background workers. For instance, you can have a "Controller" script send commands to a "Worker" script through the pipe, and use trap signals to manage the lifecycle of both processes gracefully.

Note that pipes are blocking by default: the sender will wait until a reader opens the pipe, and vice-versa. This built-in synchronization makes them much safer than reading/writing to standard files, where you would otherwise need the Resource Locking techniques we learned earlier to prevent data corruption.

Key Takeaway: Named pipes allow scripts to communicate as if they were part of a single pipeline, using a persistent filesystem object to facilitate real-time data exchange.