Find a course

Module 3: Redirection, Pipes and Text ProcessingLesson 7 of 1311 min

Redirection and Pipes

Understand standard input, output and error, redirect them with >, >> and 2>, discard noise with /dev/null, and chain commands with the pipe.

Step 1 of 12Learn

Small tools, joined together

Here is a question a manager might ask: "Which 5 IP addresses hit our website most often today?" There is no single Linux command called top-five-visitors. Instead, an admin types something like this:

$ cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head -5

Five small tools, each doing one job, connected by the | character. That design idea, small programs that do one thing well and work together, is called the Unix philosophy, and it is why the command line is so flexible. By the end of the next lesson you will be able to read that line word by word.

The glue is the way programs handle input and output. Every program starts with three channels, called streams:

StreamNumberDefault
Standard input (stdin)0the keyboard
Standard output (stdout)1the terminal screen
Standard error (stderr)2the terminal screen

Normal results go to stdout; error messages go to stderr. Both show up on your screen, which is why they look the same, but they are separate channels. That separation lets you save the results to a file while still seeing the errors, or throw the errors away while keeping the results.

Step 2 of 12Practice · Diagram

Every program has three streams

Which stream carries a "Permission denied" message?

Tap the shape that answers the question, then press Check.

Every program has three streamsParts diagram: A running program, stdin (0): input, stdout (1): results, stderr (2): errors.A runningprogramstdin (0):inputstdout (1):resultsstderr (2):errors
A running program
stdin (0): input

Comes from the keyboard by default, or from a file or pipe.

stdout (1): results

Normal output. Goes to the screen by default.

stderr (2): errors

Error messages. Also goes to the screen, but on a separate channel.

Step 3 of 12Learn

Redirecting output to files

Redirection changes where a stream goes.

  • > sends stdout to a file, replacing the file if it already exists: ls -l /etc > etc-list.txt.
  • >> appends stdout to the end of a file, keeping what was there: echo "backup done" >> backup.log.
  • 2> redirects stderr: find / -name "*.conf" 2> errors.txt keeps the results on screen and files the "Permission denied" messages away.
  • 2>&1 sends stderr to wherever stdout is currently going. command > all.log 2>&1 captures both streams in one file. The order matters: the stdout redirect comes first, then 2>&1 copies it.
  • < feeds a file into stdin: sort < names.txt.

A special file, /dev/null, discards everything written to it. find / -name passwd 2>/dev/null hides all the permission errors and shows only real matches.

The danger lives in >. Typing > important.txt by mistake empties the file instantly. A classic mistake is sort data.txt > data.txt: the shell truncates data.txt to zero bytes before sort even starts reading it, so you end up with an empty file. Write to a new file, then rename it. In Bash, set -o noclobber makes > refuse to overwrite existing files.

Step 4 of 12Practice · Match the pairs

Match each redirection to what it does.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. cmd > out.txt
  2. cmd >> out.txt
  3. cmd 2> err.txt
  4. cmd > all.txt 2>&1
  5. cmd 2>/dev/null

Step 5 of 12Practice · True or false

Running sort names.txt > names.txt sorts the file in place.

Step 6 of 12Compare

Redirection operators at a glance

Aspect>>>2>> file 2>&1
Redirectsstdoutstdoutstderrstdout and stderr
Existing fileEmptied firstKept, new lines added at the endEmptied firstEmptied first
Examplels -l > list.txtecho done >> backup.logfind / -name x 2> errors.txtbackup.sh > backup.log 2>&1

Step 7 of 12Learn

The pipe

Redirection connects a program to a file. A pipe, written |, connects a program to another program: the stdout of the left command becomes the stdin of the right one. No temporary file is needed.

$ ls -l /etc | less
$ cat access.log | grep "404" | wc -l
$ ps aux | grep nginx

The first lets you scroll through a long listing. The second counts the requests that returned a 404 error. The third finds running nginx processes.

Many commands, like grep, wc and sort, read from stdin when you don't give them a file name. That is what makes them pipe-friendly. (In the second example, grep "404" access.log | wc -l does the same job with one fewer program; cat at the start of a pipe is harmless, but not needed.)

Pipelines are built step by step. Run the first command and look at the output. Add | head to keep it short while you experiment. Then add the next filter, check again, and so on. If a pipeline gives a strange result, remove commands from the end until the output looks right; the last one you removed is where the problem is.

Note that a pipe only carries stdout. Error messages still go to the screen unless you add 2>&1 before the pipe.

tee lets you save and pass on at the same time: command | tee output.txt | grep error writes everything to a file and still sends it down the pipe.

Data flowing from grep through a pipe into wccat loggrep 404wc -l||each stdout feeds the next stdin

Step 8 of 12Practice · Put in order

Build a pipeline step by step: put these stages in the order data should flow to count how many lines in app.log contain "timeout", ignoring case.

Drag the items, or use the arrow buttons, to put them in order.

  1. grep -i timeout
  2. wc -l
  3. cat app.log

Step 9 of 12Note

Step 10 of 12Note

Step 11 of 12Practice · Select all that apply

Which commands will show matching results on screen while hiding "Permission denied" errors? Select all that apply.

Select all that apply.

Step 12 of 12Practice · What would you do?

What would you do?

A nightly backup script runs backup.sh > backup.log. When it fails, backup.log contains only the normal progress lines and none of the error messages. What should change?