← All lessons
Command line basics · Lesson 7 of 7

Pipes and redirection

Commands write their results to standard output, which is normally the screen. > sends it to a file instead, replacing whatever the file held. >> adds to the end. < feeds a file in as the command's input.

$ echo mallard > ducks.txt
$ echo teal >> ducks.txt
$ cat ducks.txt
mallard
teal

Careful: > empties the file first, before the command even runs. sort list.txt > list.txt leaves you with an empty file. Write to a new name, then rename it.

The pipe, |, connects commands: the output of the left one becomes the input of the right one. This is the Linux way: small tools that each do one thing, joined into something bigger. ls | wc -l counts the files in a folder.

grep prints the lines that contain a word: grep error app.log. Add -i to ignore case, -v to show the lines that don't match, -c to count them and -n to show line numbers. sort sorts lines and uniq drops repeats that sit next to each other, so you sort first.

$ cat visits.txt | sort | uniq
bob
dana
sam

Errors go to a second stream, standard error, so they still show on screen when you redirect output. 2> redirects errors: find / -name hosts 2> /dev/null hides the permission errors. /dev/null is a bin that throws away anything written to it.

Practice

Save the output of ls to a file called files.txt, replacing it if it exists.

More info

Quick reference

cmd > fileOutput to a file, replacing it.
cmd >> fileAdd output to the end of a file.
cmd < fileUse a file as input.
a | bPipe: a's output is b's input.
grep -i -v -c -n wordFind lines: ignore case, invert, count, numbers.
sort, uniq, sort -uSort lines; drop neighbouring repeats; both.
2> /dev/nullThrow away error messages.

The other Linux courses