4. Pipes, Redirection, and the Shell's Plumbing

How data flows between programs at the kernel level

The pipe character | is the most important symbol on the Unix command line. It takes the output of one program and feeds it as input to another. An entire philosophy of software — small tools that do one thing well — depends on this single mechanism.

But pipes are just one piece of a larger system. Underneath, the shell manipulates file descriptors, kernel buffers, and process relationships every time you type a command. Understanding this plumbing makes the difference between copying commands from Stack Overflow and truly controlling what happens to your data.

File Descriptors — The Foundation

Every running process has a table of file descriptors — small integers that point to open files, devices, or pipes. Three are created automatically:

FD Name Default destination
0 stdin Keyboard (terminal input)
1 stdout Terminal screen
2 stderr Terminal screen

When a program calls read(), it reads from FD 0. When it calls write(), it writes to FD 1. Error messages go to FD 2. The program doesn't know (or care) whether these point to a terminal, a file, or a pipe — it just reads and writes to numbered descriptors.

A program's view

# From the program's perspective:
read from FD 0   → gets input (keyboard? file? pipe? doesn't matter)
write to FD 1    → sends output
write to FD 2    → sends errors

This abstraction is the key insight. Redirection is simply the shell changing where FDs 0, 1, and 2 point before the program starts.

Output Redirection: > and >>

The > operator redirects stdout (FD 1) to a file:

echo "hello" > greeting.txt

What the shell actually does:

  1. fork() a child process
  2. In the child, open("greeting.txt", O_WRONLY | O_CREAT | O_TRUNC) → returns some FD, say 3
  3. dup2(3, 1) — copy FD 3 onto FD 1, so stdout now points to the file
  4. close(3) — clean up the extra descriptor
  5. exec("echo", "hello") — echo writes to FD 1, which is now the file

The program never knows the difference. It calls write(1, "hello\n", 6) just like it always would.

Append with >>

>> works the same way but opens the file with O_APPEND instead of O_TRUNC:

echo "line 1" > log.txt    # creates or overwrites
echo "line 2" >> log.txt   # appends

Input Redirection: <

The < operator redirects stdin (FD 0) from a file:

wc -l < README.md

The shell opens README.md and copies it onto FD 0 before executing wc. Notice the difference from wc -l README.md — with redirection, wc doesn't know the filename; it just reads from stdin.

Stderr Redirection: 2>

Since stderr is FD 2, you redirect it with 2>:

# Save errors to a file, stdout still goes to the terminal
gcc broken.c 2> errors.txt

Combining stdout and stderr

A common pattern is sending both streams to the same file:

# Method 1: redirect stdout to file, then stderr to stdout
command > output.txt 2>&1

# Method 2: shorthand (bash 4+)
command &> output.txt

The order in 2>&1 matters. The shell processes redirections left to right:

Order matters

# Correct: stdout to file, then stderr to where stdout now points (the file)
command > out.txt 2>&1

Wrong: stderr to where stdout currently points (terminal), then stdout to file

command 2>&1 > out.txt

stderr still goes to the terminal!

Pipes: Connecting Processes

A pipe connects the stdout of one process to the stdin of another:

cat access.log | grep "404" | awk '{ print $1 }' | sort | uniq -c | sort -rn

Under the hood, the shell:

  1. Calls pipe() — the kernel creates a buffer with two FDs: one for reading, one for writing
  2. fork()s two child processes
  3. In the left child: copies the pipe's write-end onto FD 1 (stdout)
  4. In the right child: copies the pipe's read-end onto FD 0 (stdin)
  5. exec()s both programs

The kernel buffer (typically 64 KB on Linux) sits between them. The writer blocks if the buffer is full; the reader blocks if it's empty. This automatic backpressure means pipes work correctly regardless of how fast each side runs.

Pipe buffer in action

# This works even though yes produces infinite output:
yes | head -5
# y
# y
# y
# y
# y
# head exits after 5 lines → write end gets SIGPIPE → yes terminates

Pipe vs. Redirection

Pipes connect processes. Redirection connects a process to a file.

# Pipe: grep's stdout → wc's stdin (two processes)
grep "error" log.txt | wc -l

# Redirection: file → wc's stdin (one process)
wc -l < log.txt

Piping Stderr

By default, pipes only carry stdout. To pipe stderr as well:

# Merge stderr into stdout, then pipe
command 2>&1 | grep "error"

# Pipe only stderr (swap FDs using FD 3 as temp)
command 3>&1 1>&2 2>&3 | grep "error"

In bash 4+, |& is shorthand for 2>&1 |:

command |& grep "error"

Here Documents and Here Strings

Here document (<<)

Feed multi-line input to a command inline:

cat <<EOF
Hello, $USER.
Today is $(date).
EOF

The shell expands variables and command substitutions inside the heredoc. To prevent expansion, quote the delimiter:

cat <<'EOF'
This $variable is not expanded.
EOF

Here string (<<<)

Feed a single string as stdin:

wc -w <<< "count these words"
# 3

Process Substitution: <() and >()

Process substitution lets you use a command's output where a filename is expected. The shell creates a temporary named pipe (or /dev/fd/N path) behind the scenes.

# Compare the output of two commands
diff <(ls dir1) <(ls dir2)

<(ls dir1) becomes something like /dev/fd/63 — a path that, when read, produces the output of ls dir1.

Compare sorted vs. unsorted

diff <(sort file.txt) file.txt

Feed multiple streams to a command

# paste needs filenames, not stdin
paste <(cut -f1 data.tsv) <(cut -f3 data.tsv)

This is one of the most underused features in bash. It bridges the gap between "pipes connect stdin/stdout" and "this tool expects a filename."

The /dev/ Special Files

Several virtual files are useful in redirection:

Path Purpose
/dev/null Discards all data written to it
/dev/zero Produces infinite zero bytes
/dev/urandom Produces random bytes
/dev/stdin Symlink to FD 0
/dev/stdout Symlink to FD 1
/dev/stderr Symlink to FD 2

Suppress output

# Discard stdout
command > /dev/null

Discard everything

command &> /dev/null

tee — Split a Stream

tee reads from stdin and writes to both stdout and a file. It's the pipe fitting that lets you tap into a stream without breaking it:

# Save intermediate results while continuing the pipeline
cat access.log | grep "500" | tee errors.txt | wc -l

Use tee -a to append instead of overwrite.

Multiple tees

command | tee file1.txt | tee file2.txt | final_command

Named Pipes (FIFOs)

A named pipe is a pipe that lives on the filesystem. One process writes to it, another reads from it — they don't need to be started by the same shell:

# Terminal 1: create and read from a named pipe
mkfifo /tmp/mypipe
cat /tmp/mypipe    # blocks waiting for data

# Terminal 2: write to the named pipe
echo "hello" > /tmp/mypipe   # cat in terminal 1 prints "hello"

Named pipes are useful for inter-process communication without temporary files.

Putting It All Together

Here's a pipeline that analyzes web server logs — finding the top 10 IP addresses that got 404 errors in the last hour:

cat access.log \
  | awk -v cutoff="$(date -d '1 hour ago' '+%d/%b/%Y:%H')" \
        '$4 > "["cutoff && $9 == 404 { print $1 }' \
  | sort \
  | uniq -c \
  | sort -rn \
  | head -10

Each program does one thing:

  • cat reads the file
  • awk filters by time and status, extracts IPs
  • sort groups identical IPs together
  • uniq -c counts consecutive duplicates
  • sort -rn sorts by count descending
  • head -10 takes the top results

No temporary files. No scripts. Just data flowing through pipes.

Common Pitfalls

The useless use of cat

# Unnecessary — grep can read files directly
cat file.txt | grep "pattern"

# Better
grep "pattern" file.txt

This matters less than people argue about, but it does add an extra process and a pipe buffer for no reason.

Broken pipe signals

When the reading end of a pipe closes (e.g., head exits after 10 lines), the writer gets a SIGPIPE signal and terminates. This is usually what you want, but it can cause confusing exit codes in scripts.

Variable scope in pipes

Each segment of a pipeline runs in a subshell. Variables set inside a pipe don't affect the parent:

# This doesn't work as expected
cat file.txt | while read line; do count=$((count + 1)); done
echo "$count"   # empty!

# Fix: use process substitution
while read line; do count=$((count + 1)); done < <(cat file.txt)
echo "$count"   # correct

Summary

  • Every process has file descriptors: 0 (stdin), 1 (stdout), 2 (stderr)
  • Redirection (>, <, 2>) changes where FDs point before a program starts
  • Pipes (|) connect one process's stdout to another's stdin via a kernel buffer
  • 2>&1 merges stderr into stdout — order of redirections matters
  • Process substitution (<()) creates a filename from a command's output
  • Here documents (<<) and here strings (<<<) provide inline input
  • tee splits a stream to both a file and stdout
  • Small tools + pipes = composable data processing without temporary files