16 min read
Linux pipes and redirection: |, > and 2>&1
In one sentence: Every program reads from one input and writes to two outputs: one for results and another for errors. With > you send the output to a file, and with | you hand it to another program. That way, a few small commands read a log of thousands of lines in a second.
What you will learn
- Tell stdin, stdout and stderr apart, and send each output wherever you want with >, >>, 2>, 2>&1 and /dev/null.
- Chain programs with | and count lines with cut, sort and uniq -c.
- Read a program's exit code with $? and decide what runs next with && and ||.
- Investigate a server log from the terminal: who asks the most, what fails and when.
Before you start, read: 02-files-and-text.md
The problem
Section titled “The problem”Imagine you run an online shop and a customer writes to you: “Yesterday afternoon I tried to pay three times and couldn’t.” You log in to the server. There’s the LogA text file where a program writes down what happens, one line for each thing. A web server’s has a line for each request it receives, and it’s the first thing you look at when something fails.Go to definition: a file where the web server writes down one line for every RequestThe message a client sends to a server to ask for something, for example “give me the home page.”Go to definition it receives. Yesterday’s has 974 lines.
From lesson 2 you know how to search it with grep. But you don’t want to read lines: you want answers. How many payments failed? Starting when?
No single command answers that. But the terminal lets you chain small commands: one keeps the time from each line, another sorts them and another counts them. Together, they answer in a single line.
The analogy
Section titled “The analogy”The analogy
Imagine a kitchen with several cooks in a row. Each one does a single thing: one peels, another chops and another plates. Each one gets what they need through a hatch on their left, and puts what they’ve made through another hatch on their right.
If you put two cooks side by side, the first one’s outgoing hatch is the second one’s incoming hatch: that’s a PipeThe terminal’s | symbol: it connects two programs, so what the first one writes reaches the second one as input.Go to definition. If, instead of opening onto the next cook, the hatch opens onto the fridge, what comes out is stored for later: that’s a redirection.
If a cook finds a rotten tomato, they don’t put it on the plate: they shout it out, so the head chef hears it even though the plate keeps moving. And when they finish, each one says “done” or “that went wrong.”
Where the analogy breaks down
- In the kitchen, the plate moves on whole. In the terminal, lines go through one by one and all the programs work at the same time, although
sort, for example, has to wait until it has them all. - What you “put in the fridge” with
>replaces what was there; a real fridge doesn’t throw anything away. - A program’s “done” is a number, and the opposite of what you’d expect: 0 means it went well.
How it really works
Section titled “How it really works”One program, one input and two outputs
Section titled “One program, one input and two outputs”Go to your practice folder, where you downloaded access.log in lesson 2, and ask ls for two files, one that exists and one that doesn’t:
cd ~/backend-course/phase-1ls access.log missingls: missing: No such file or directoryaccess.log(On Linux and WSL, the error says ls: cannot access 'missing'.) Two lines come out mixed together on the screen, but ls wrote them through two different places. Every program the shell starts has three channels open, numbered 0 to 2:
| Number | Name | What for | Unless you say otherwise |
|---|---|---|---|
| 0 | stdinStandard input, the channel through which a program receives data. Unless you say otherwise, it’s what you type; with a pipe, it’s what the previous program writes.Go to definition, standard input | What the program reads | What you type |
| 1 | stdoutStandard output, the channel through which a program writes its results. Unless you say otherwise, it goes to the screen; it can be sent to a file or to another program.Go to definition, standard output | The results | The screen |
| 2 | stderrStandard error, a second output channel that programs use for warnings and errors. It goes to the screen even when the normal output goes to a file or to another program.Go to definition, standard error | Errors and warnings | The screen |
The access.log line came out through output 1, and the error through output 2. Since both go to the screen, you see them together. But they’re different channels, and you can send each one somewhere else.
Sending the output to a file
Section titled “Sending the output to a file”> sends standard output to a file instead of the screen:
ls access.log missing > list.txtcat list.txtls: missing: No such file or directoryaccess.logThe error still shows up on the screen, because > only redirects output 1. The access.log line no longer does: it ended up in list.txt, and cat shows it afterwards. If the file doesn’t exist, > creates it.
>overwrites: if the file already had something in it, the shell empties it before starting the program, without asking.>>appends to the end: what was there stays. It’s useful for collecting results into a report.
Separating the errors
Section titled “Separating the errors”The channel number goes right before >. Since > is the same as 1>, standard error is sent with 2>:
ls access.log missing 2> errors.txtcat errors.txtaccess.logls: missing: No such file or directoryNow it’s the other way around: the result shows up on the screen and the error is saved. Three very common variants:
> all.txt 2>&1puts both outputs in the same file.2>&1reads “send output 2 wherever output 1 is going right now.” The&says that1is a channel and not a file called “1.”2> /dev/nullthrows the errors away./dev/nullis a special file that swallows everything you write to it.>&2does the opposite of2>&1: it sends normal output to standard error. That’s how scripts write their warnings, as you’ll see in lesson 8.
Order matters, because the shell reads redirections from left to right. In 2>&1 > all.txt, output 2 goes where output 1 was at that moment, the screen, and only output 1 ends up in the file.
Connecting programs with a pipe
Section titled “Connecting programs with a pipe”| (the vertical bar; on a US keyboard, Shift + \, the backslash key) connects one program’s standard output to the next one’s standard input. For example, to count the 404s in the log with two programs from lesson 2:
grep '" 404 ' access.log | wc -l 64grep lets the lines with a 404 code through and, instead of writing them on the screen, hands them to wc -l, which counts them. Neither one knows the other exists: grep writes to its output, wc reads from its input and the shell connects them.
The pipe only carries output 1. Errors still go to the screen:
ls access.log missing | wc -lls: missing: No such file or directory 1wc only got access.log. To send it the error too, write 2>&1 |.
Each piece of a line has its number
Section titled “Each piece of a line has its number”In lesson 2 you saw what each part of a log line says. To get answers out of it, you still need to know each part’s number. This is the first line:
203.0.113.50 - - [01/Oct/2026:00:00:41 +0000] "GET /robots.txt HTTP/1.1" 200 12378 "-" "ExampleBot/1.0 (+https://example.com/bot)"If you split it at the spaces, each piece is a field, and they’re counted from 1:
| Field | In this line | What it is |
|---|---|---|
| 1 | 203.0.113.50 |
The IP of whoever is asking |
| 4 | [01/Oct/2026:00:00:41 |
The day and time |
| 6 and 7 | "GET and /robots.txt |
What they’re asking for: the method and the path |
| 9 | 200 |
The response’s Status codeA three-digit number at the start of every HTTP response that sums up what happened. 200 means “all good,” 404 “that doesn’t exist” and 400 “your request is malformed.”Go to definition |
| 10 | 12378 |
How many bytes the response took up |
Cut, sort and count
Section titled “Cut, sort and count”With three programs you can count almost anything in a log:
cutkeeps one piece of each line.-d' 'says which character to split at (here, the space) and-f9, which field to keep.sortsorts the lines. With-nit sorts them as numbers, and with-r, in reverse, from largest to smallest.uniq -cmerges identical lines that come one after another and writes in front how many there were.
Here’s how to count the status codes in the log, step by step. First, cut on the first line, to check that field 9 is the code:
head -1 access.log | cut -d' ' -f9200Now on the whole log, sorting so identical codes end up together, and counting them:
cut -d' ' -f9 access.log | sort | uniq -c 865 200 19 301 64 404 26 500And so the most frequent comes first, you sort again, this time by the number:
cut -d' ' -f9 access.log | sort | uniq -c | sort -rn 865 200 64 404 26 500 19 301Yesterday, the server answered fine 865 times, didn’t find what it was asked for 64 times and failed 26 times. Along the way, the data flows like this:
- access.log974 whole lines
cut -d' ' -f9
- 974 codes200, 200, 200, 301…
sort
- 974 sorted codesthe 200s together, then the 301s…
uniq -c
- 4 lineseach code with its count
sort -rn
- The same 4 linesfrom largest to smallest
On Linux and WSL, uniq -c puts more spaces in front of the numbers ( 865 200), and wc -l puts none (64). It’s just formatting: the numbers are the same.
Every program ends with a code
Section titled “Every program ends with a code”When a program finishes, it leaves a number behind: its Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition. It doesn’t show up on the screen, but the shell keeps it, and echo $? shows it to you:
grep '" 500 ' access.log > /dev/nullecho $?0grep found lines (you sent them to /dev/null so you wouldn’t see them), so it finished with 0. 0 means everything went well, and any other number means something failed. grep has three:
| Code | What it means for grep |
Example |
|---|---|---|
| 0 | It found at least one line | grep '" 500 ' access.log |
| 1 | It didn’t find any | grep '" 503 ' access.log (there are no 503s) |
| 2 | There was an error | grep '" 500 ' acess.log (the file doesn’t exist) |
$? holds the code of the last command, so you have to check it right afterwards: echo itself changes it.
Chaining based on the result
Section titled “Chaining based on the result”With the exit code, the shell decides what to do next:
a && brunsbonly ifasucceeded (finished with 0).a || brunsbonly ifafailed.a ; balways runsb, whatever happens witha.
grep '" 500 ' access.log > /dev/null && echo "There are 500 errors"grep '" 503 ' access.log > /dev/null || echo "No 503s"There are 500 errorsNo 503s&& prevents chains of errors. With cd old && rm *.txt, if the old folder doesn’t exist, rm doesn’t run; with ;, it would delete the .txt files wherever you happened to be. When a step depends on the previous one, join them with &&.
Try it
Section titled “Try it”The goal: you’re the one keeping an eye on the example.com shop, and yesterday’s log, from October 1, hides four stories. You already know one: the scanner from lesson 2. Find the other three without opening it, using only pipes. Everything happens in your terminal, inside your practice folder.
The outputs are from a Mac. On Linux and WSL, the numbers from uniq -c have more spaces in front, and the ones from wc -l have none; there are no other differences.
1. Check that you have the log
cd ~/backend-course/phase-1wc -l access.logWhat you will see:
974 access.logIf it answers No such file or directory, download it as in lesson 2, with curl -O https://backenddesdecero.com/practicas/access.log. It has to say 974: the log is the same for everyone, so your numbers will be the ones on this page.
2. Who asks you for the most?
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head -5What you will see:
144 203.0.113.5065 192.0.2.1040 198.51.100.2336 192.0.2.25323 203.0.113.99The status code recipe, with field 1, the IP, and head -5 to keep the top five. The first one asks for more than twice as much as the second. Investigate it.
3. Who is 203.0.113.50?
grep '^203.0.113.50 ' access.log | cut -d'"' -f6 | sort | uniq -cgrep '^203.0.113.50 ' access.log | cut -d: -f2 | sort | uniq -c | head -3What you will see:
144 ExampleBot/1.0 (+https://example.com/bot) 6 00 6 01 6 02The space after the IP, as in lesson 2, says that it ends there. The ^ means “at the start of the line”: that way it only finds the IP in field 1.
The first command splits at the double quotes (-d'"'): the sixth piece is the program’s name. All 144 requests are from ExampleBot. The second splits at the colons, and field 2 is the hour: it asks 6 times every hour, from 00 to 23, like clockwork.
First story: it’s a robot (a bot) that crawls the shop all day, like search engines do. It does no harm: it’s just the one that asks the most.
4. Who asks for what doesn't exist?
grep '" 404 ' access.log | cut -d' ' -f1 | sort | uniq -c | sort -rn | head -3What you will see:
40 198.51.100.23 2 203.0.113.50 2 203.0.113.184First you filter the lines with a 404, and then you count their IPs. The quotes and spaces in '" 404 ' look for the 404 in the code field, and not inside some other number.
Of the 64 404 errors, 40 come from a single IP: 198.51.100.23, the scanner you found in lesson 2. The rest have 2 or fewer: broken links and mistyped addresses.
5. What was 198.51.100.23 looking for, and when?
grep '^198.51.100.23 ' access.log | cut -d' ' -f4,7,9 | head -5What you will see:
[01/Oct/2026:03:12:23 /.env 404[01/Oct/2026:03:12:24 /.env.backup 404[01/Oct/2026:03:12:25 /.git/config 404[01/Oct/2026:03:12:26 /.git/HEAD 404[01/Oct/2026:03:12:27 /wp-login.php 404-f4,7,9 keeps the time, the path and the code. Now you can see what else the scanner tried, almost one request per second: besides .env, the Git configuration and the WordPress admin login page.
The scanner’s story, complete: it tried well-known addresses in case the shop had left them exposed, and they all got a 404. Change head -5 to tail -2 and you’ll see that it finished at 03:13.
6. Requests per hour
cut -d: -f2 access.log | sort | uniq -cWhat you will see:
13 0012 0114 0251 03 6 0413 0524 0640 0742 0844 0987 1083 1149 1237 1371 1446 1524 1622 1745 1865 1975 2072 2126 2213 23Without the final sort -rn, because here you want the hours in order. Normal for a shop: little in the early hours, more in the late morning and another peak in the evening. One hour doesn’t fit: 03, with 51 requests. You already know why: 40 of them are from the scanner.
7. When did the 500 errors start?
grep '" 500 ' access.log | cut -d: -f2,3 | sort | uniq -cWhat you will see:
1 14:05 1 14:07 2 14:08 1 14:09 3 14:10 2 14:11 2 14:13 1 14:14 1 14:16 2 14:17 2 14:21 2 14:22 2 14:23 4 14:24With -f2,3, cut keeps the hour and the minute. The 26 500 errors fall within just twenty minutes: from 14:05 to 14:24. There are none before or after.
8. What was failing?
grep '" 500 ' access.log | cut -d' ' -f6,7 | sort | uniq -cWhat you will see:
1 "GET /api/products?page=325 "POST /api/orders25 of the 26 failures are POST /api/orders: submitting an order.
Second story: between 14:05 and 14:25, the shop couldn’t charge for orders. If you count the IPs in those lines, you’ll see that some repeat: people who, like your customer, tried again.
9. Save the report
echo "500 errors per minute" > report.txtgrep '" 500 ' access.log | cut -d: -f2,3 | sort | uniq -c >> report.txt && echo "Report saved"head -3 report.txtWhat you will see:
Report saved500 errors per minute 1 14:05 1 14:07The first line creates report.txt with a title, and the second appends the count below it with >> (with > you would have erased the title). && echo only writes “Report saved” if the pipe succeeded.
One story is left. This time, write the commands yourself, without copying them:
Challenge: the second IP that asks the most, 192.0.2.10, isn’t a robot. At what hours does it ask? How many different browsers does it use? What do you think it is?Show answer
grep '^192.0.2.10 ' access.log | cut -d: -f2 | sort | uniq -cgrep '^192.0.2.10 ' access.log | cut -d'"' -f6 | sort | uniq | wc -luniq without -c leaves one line of each, and wc -l counts how many are left. The first command answers with hours from 09 to 16: 8 09, 4 10, 13 11, 1 12, 12 13, 20 15 and 7 16. The second answers 4: an iPhone, a Mac, a Windows PC and a Linux one.
Third story: it’s an office. Several people, each with their own computer or phone, go out to the internet through the same router, and the shop sees them all as a single IP. It’s the NATNAT stands for Network Address Translation.What the router does on the way out to the internet: it replaces your device’s private IP address with its own public one, and notes the change so it can undo it in the replies.Go to definition from Phase 0, lesson 5. It only asks during working hours, and hardly at all at lunchtime.
You have already seen it
Section titled “You have already seen it”- The “Error 404” and “Error 500” pages you come across while browsing: each one usually gets written down in that server’s log.
- A spreadsheet, when you sort a column and count how many times each value appears with a pivot table: it’s
sort | uniq -cwith a mouse.
And if you code:
npm run build && npm run deploy: if the build fails, nothing gets published. It’s this lesson’s&&.- In Node,
console.logwrites to stdout andconsole.error, to stderr. - A GitHub Actions step turns red when a command finishes with a code other than 0, like the one
process.exit(1)leaves.
Common mistakes
Section titled “Common mistakes”- Searching for the bare number.
grep -c 404 access.loganswers 113, not 64: it also counts the 49 responses that take up4047bytes. Anchor what you’re looking for to its field, as in'" 404 ', or cut it out first withcut. uniq -cwithout asortfirst.uniqonly merges identical lines that come one after another. Without sorting,cut -d' ' -f9 access.log | uniq -cstarts with19 200,1 301,21 200…: the same code, counted in bits. Always sort first.- Reading and writing the same file.
sort access.log > access.logleaves the file empty: the shell empties it because of the>beforesortstarts reading it. Write to another file; if it happens to you with the log, download it again. - A space in
2>. Inls access.log missing 2 > errors.txt, the shell sees an argument2and a regular>:lslooks for a file called2, and the normal output ends up inerrors.txt. The2goes right up against the>. - Checking
$?after a pipe. It’s the code of the last program.cut -d' ' -f1 acess.log | sort | uniq -cwrites an error, but$?gives 0, becauseuniqsucceeded. In lesson 8 you’ll see how to make a pipe fail if any of its parts fails.
Summary
Section titled “Summary”- Every program has one input (stdin, 0) and two outputs: the results (stdout, 1) and the errors (stderr, 2).
>sends output to a file and overwrites it;>>appends to the end;2>sends the errors;2>&1joins the errors with the output, and/dev/nullswallows whatever you send it.|connects one program’s output to the next one’s input. Withcut,sortanduniq -cyou can count whatever you want in a log.- Every program finishes with a code: 0 if it went well and another number if not.
$?shows it,&&continues only if it went well and||, only if it failed.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- The Linux Command Line, by William Shotts: chapter 6, “Redirection,” covers the same ground as this lesson with more examples.
- Redirections, in the bash manual: every way to redirect, including the ones we haven’t covered.