Linux Pipes and Redirection: Chain Commands Together
You want to know how many files sit in a folder, or which page of a website gets the most visits, and scrolling through hundreds of lines will not tell you. This lesson explains pipes and redirection: the three streams every command has, how to send them to files, how the vertical bar chains commands, and two classic slip-ups.
Three streams: stdin, stdout and stderr
Every process, a running program (lesson 3), starts with three streams: channels that carry text in or out. Each has a name and a number, its file descriptor.
- Standard input, stdin (0): where a command reads input. By default, what you type in the terminal.
- Standard output, stdout (1): its normal results. By default, the terminal window.
- Standard error, stderr (2): its error messages. Also the terminal by default, so errors and results look mixed even though they travel separately.
Redirection changes where a stream goes. The shell, the program that reads your commands (lesson 4), sets it up before the command starts. In the diagram, notice that each stream goes to exactly one place.
Redirection: send output to a file, or read from one
> sends stdout into a file. echo hello > out.txt prints nothing: hello went into out.txt in your working directory, the folder you are in. The shell creates the file if it is missing and, if it exists, empties it first, without asking.
>> appends: it adds to the end of the file and keeps what was there, creating the file if needed.
< makes a command read a file as its stdin. wc -l names.txt (wc means word count, and -l asks for lines) prints the line count and the file name. wc -l < names.txt prints only the count, because wc reads stdin and never learns the name.
2> redirects stream 2: ls /nothing 2> err.txt keeps the screen clean and puts the "No such file or directory" message in err.txt. Plain > means 1>. 2> /dev/null throws errors away, since /dev/null discards whatever is written to it (lesson 5).
The vertical bar: one command feeds the next
The vertical bar |, called a pipe, connects the stdout of the command on its left to the stdin of the command on its right. In ls /etc | wc -l, the names in /etc never reach the screen: they flow into wc -l, which counts the lines and prints one number.
This works because ls checks where its output goes: columns in a terminal, but one name per line into a pipe or a file. In the flowchart, follow the error path too.
The shell starts both commands together. The pipe is a buffer, a small holding area in memory kept by the kernel, the core of the operating system (lesson 2). wc reads lines as soon as ls writes them, and if wc falls behind, ls waits. To save the result, redirect the end of the line: ls /etc | wc -l > count.txt.
Small tools, each doing one job
Each of these commands does one small job and, given no file name, reads stdin, so it can sit anywhere in a chain:
sortputs lines in order;-ncompares them as numbers and-rreverses the order.uniqmerges repeated lines into one, but only repeats that sit next to each other, so you sort first;-cadds a count to each line.headkeeps the first 10 lines andtailthe last 10;head -n 3keeps 3.wc -lcounts lines.
Suppose access.log is a web server's log, its record of visits, simplified to one page name per visit. Real logs hold more on each line, such as the time, so you would first cut out one column (lesson 9 shows how). The chain in the diagram finds the most visited pages. Watch the lines change at each stage.
Build your own chains the same way: run the first command, check its output, then add one | command at a time. Here cat only prints the file, so starting with sort access.log gives the same answer.
Two common slip-ups
The bucket is emptied first
> never asks: echo milk > shopping.txt replaces a whole list with one line, where >> would add it. sort names.txt > names.txt even leaves the file empty, because the shell empties it before sort starts reading. Write to a new file instead, then rename it with mv.
Errors do not travel down the bar
The pipe carries only stdout. In ls /nothing | wc -l, the error still appears on screen and wc prints 0, because it received no lines.
Add 2>&1 before the bar to send errors along too. It means "send stream 2 wherever stream 1 goes now", and the & marks 1 as a stream, not a file named 1. ls /nothing 2>&1 | wc -l prints 1, for the error line.
Order matters with files. ls /nothing > all.txt 2>&1 puts both streams in all.txt, but with 2>&1 > all.txt the error stays on screen: stream 2 copied where stream 1 pointed at that moment, the terminal, before stream 1 moved to the file.
Check yourself
After sort names.txt > names.txt, the file is empty. Why, and what should you type instead?
The shell empties names.txt for > before sort starts, so sort reads nothing. Write to a new file, as in sort names.txt > sorted.txt.
ls /nothing | wc -l prints an error message, then 0. Why does wc not count the message?
The message goes to stderr, stream 2, and the pipe carries only stdout, stream 1, so it goes straight to the screen. With 2>&1 before the bar, wc counts it.
Why does uniq -c on an unsorted log list /home more than once?
uniq merges only repeats that sit next to each other, so scattered /home lines form separate runs, each counted alone. Sorting first puts identical lines together.