Terminal commands are small: grep only filters lines, wc only counts, and sort only sorts. A pipe (|) joins these commands into one chain. Then redirection (often called a redirect) with >, >> or 2> sends the result to a file instead of the screen. A pipe chain is like a conveyor belt in a factory: each worker takes an item off the belt, does one job, and puts it back for the next worker. The belt is the pipe, each worker is one command, and the items are data, for example lines of text. At the end of the belt the item goes on display (the screen), or into a box (a file) if you ask for it.
Three channels: stdin, stdout, stderr
Every running program has three data channels, each with a number:
| Number | Name | What it carries | Default |
|---|---|---|---|
| 0 | stdin (standard input) | data going into the program | keyboard |
| 1 | stdout (standard output) | the normal result | screen |
| 2 | stderr (standard error) | error messages | screen |
stdout and stderr both appear on the screen, so they look like one. They are really two separate channels. You only notice the difference when you use pipes and redirects.
Pipe: the left output becomes the right input
In this lesson, app.log is a shorter server log file, with only 6 lines:
INFO: Server started
ERROR: Database timeout
INFO: Request handled
ERROR: File not found
ERROR: Permission denied
INFO: Cache cleared
How many ERROR lines are there? This chain of three commands counts them:
$ cat app.log | grep ERROR | wc -l
3
| Stage | Command | What comes out |
|---|---|---|
| 1 | cat app.log |
the file's 6 lines |
| 2 | grep ERROR |
the 3 lines that contain ERROR |
| 3 | wc -l |
3, the number of lines wc received |
cat app.logwrites the file's contents to its stdout.|connects the left command's stdout to the right command's stdin. Sogrepdoesn't open any file:grepreads the 6 linescatsends it.grep ERRORonly passes on lines that contain the textERROR.wc -lcounts lines (-l= lines), then writes the number.wc -lis the end of the chain, so the number appears on the screen. (On macOS the number comes with a few spaces in front.)
Order matters. cat app.log | wc -l | grep ERROR prints nothing: wc -l has already turned 6 lines into the number 6, and that number doesn't contain ERROR.
One more: wc -c counts bytes, and echo always adds a newline character (an invisible mark for the end of a line) at the end of the text. So echo "hello" | wc -c gives 6: 5 letters plus 1 newline character.
Redirect: save the result to a file
Here are > and >> writing into the file notes.txt:
$ echo "first deploy" > notes.txt
$ echo "second deploy" >> notes.txt
$ cat notes.txt
first deploy
second deploy
$ echo "third deploy" > notes.txt
$ cat notes.txt
third deploy
>sends stdout to a file. If the file doesn't exist, it's created. If it does, it's emptied first, then written.>>also sends to a file, but adds to the end. The old content stays.- Output that goes into the file no longer appears on the screen.
Because > empties the file first, running echo "deploy" > notes.txt twice still leaves one line: the second write overwrites the first. For two lines, use >>.
Pipes and redirects can be combined. The stdout redirect goes at the end of the last command:
cat app.log | grep ERROR > result.txt # the 3 ERROR lines go into result.txt, the screen stays empty
cat app.log | grep ERROR | wc -l >> result.txt # the number 3 is added at the end of result.txt
The reverse of > is <: a file's contents are sent to stdin. wc -l < app.log prints just 6, while wc -l app.log prints 6 app.log. The difference: with <, wc only receives the file's contents, without its name.
Errors have their own path
When cat is asked to read a file that doesn't exist, its error message goes out through stderr:
$ cat app.log old.log | grep ERROR | wc -l
cat: old.log: No such file or directory
3
A pipe only carries stdout. The error from cat doesn't go into grep. It appears on the screen right away, and the result is still 3. To move stderr, put its number (2) in front of >. Here are three examples (npm run build is a command that builds a JavaScript project):
cat app.log old.log 2> error.txt | grep ERROR | wc -l # the screen shows only 3, the error goes into error.txt
find / -name "*.conf" 2> /dev/null # throw away every error message
npm run build > build.log 2>&1 # stdout and stderr into the same file
2>only applies to the command where2>is written. The error comes fromcat, so2> error.txtgoes right aftercat, not at the end of the chain./dev/nullis a special file: anything written there disappears. In the second example,find /writes many error messages because a normal user is not allowed to read many folders under/, and2> /dev/nullthrows them all away.2>&1means "stderr goes wherever stdout goes right now". Order matters.> build.log 2>&1sends both into the file. But2>&1 > build.logleaves errors on the screen, because when2>&1is read, stdout still goes to the screen. In bash,&> build.logis shorthand for the first one.teesplits the stream in two:npm run build | tee build.logshows the output on screen and saves it to a file at the same time.
Pipe in JavaScript: the pipe function
In this lesson's exercise, you write the same idea in JavaScript. pipe(f, g) returns a new function: the input goes into f, then f's result goes into g.
function pipe(...fns) {
return (input) => fns.reduce((value, fn) => fn(value), input);
}
const logLines = [
"INFO: Server started",
"ERROR: Database timeout",
"INFO: Request handled",
"ERROR: File not found",
"ERROR: Permission denied",
"INFO: Cache cleared"
];
const filterErrors = (lines) => lines.filter((l) => l.includes("ERROR")); // like grep ERROR
const countLines = (lines) => lines.length; // like wc -l
const countErrors = pipe(filterErrors, countLines);
console.log(countErrors(logLines)); // 3
...fnsgathers every function passed topipeinto one array (a list of values).pipedoesn't run anything yet.pipereturns a function that waits forinput.reduce(from the array methods lesson) carries the value from one function to the next.valuestarts asinput, then is replaced by each function's result.
pipe((n) => n + 1, (n) => n * 2)(3) gives 8. The number 3 goes into the first function and becomes 4, then 4 goes into the second function and becomes 8. The order is left to right, just like | in the terminal. And pipe()(5), with no functions at all, returns 5: reduce has nothing to run, so the starting value comes out.
⚠️ What makes a pipeline give the wrong result
>into the file being read.sort data.txt > data.txtemptiesdata.txtbeforesortcan read it, so the result is an empty file. Write to another file first.- Thinking errors go through the pipe or into the file.
|and>only carry stdout. Error messages still appear on screen until you use2>. - Stages in the wrong order. Each stage only sees the previous stage's output.
wc -lin the middle of a chain turns every line into one number. - In the exercise, functions running from the right, or
reducewithout a starting value.pipe(addOne, timesTwo)(3)must be8(3 plus 1, then times 2), not7. The exercise also checks that you usereduce. Andpipe()(5)must return5, so passinputas the starting value.
TL;DR: Every program has three data channels: stdin (0, data coming in), stdout (1, the normal result) and stderr (2, error messages). A pipe | connects the left command's stdout to the right command's stdin: cat app.log | grep ERROR | wc -l prints 3, the number of ERROR lines in the log file app.log. > writes stdout to a file and overwrites it, >> adds to the end of the file, and < reads a file as stdin. Errors go through stderr, so they don't follow a pipe or >. Move them with 2> file, throw them away with 2> /dev/null, or send them where stdout goes with > file 2>&1. echo "hello" | wc -c (count bytes) gives 6, because echo adds a newline character. In JavaScript, pipe(...fns) returns (input) => fns.reduce((value, fn) => fn(value), input), which runs the functions left to right.
⚡ Join commands with a pipe
Write:
cat app.log | grep ERROR | wc -l
Meaning: app.log is a server log file with 6 lines, 3 of them ERROR lines. A pipe | connects the output of the left command to the input of the right one. cat sends the file's 6 lines, grep ERROR only passes on the 3 lines that contain ERROR, and wc -l counts the lines and prints 3.
⚡ Save to a file: > and >>
Write:
echo "first deploy" > notes.txt
echo "second deploy" >> notes.txt
Guess first: > writes the output of echo into a file. echo "deploy" > notes.txt runs twice. How many lines does the file hold?
One line. > empties the file before writing, so the second write overwrites the first. >> is the one that adds to the end.
Meaning: Output that goes to a file no longer appears on the screen.
⚡ Errors have their own path
Write:
find / -name "*.conf" 2> /dev/null
Meaning: find / -name "*.conf" searches for files whose name ends in .conf, starting from the root /. A normal user is not allowed to read many folders under /, so find also writes many error messages. Error messages go out through stderr (a channel only for errors), not stdout (the channel for normal output), so they don't follow | or >. 2> moves stderr to /dev/null, a special file that throws away anything written to it.
⚡ Pipe in JavaScript
Write:
function pipe(...fns) {
return (input) => fns.reduce((value, fn) => fn(value), input);
}
Meaning: pipe(f, g) returns a new function: the input goes into f, then its result goes into g, left to right like |. The starting value of reduce is input, so pipe()(5), with no functions, returns 5.
The exercise checks that you use reduce.