Course outline · 0% complete

0/29 lessons0%

Course overview →

Redirection: sending output to files

lesson 5-1 · ~11 min · 13/29

Quiz

Warm-up: since lesson 3-1 you've been writing files with echo. What is the difference between > and >>?

Every command has three streams

Redirection is what turns commands into saved artifacts: a report written to a file instead of scrolling past, an overnight job's errors captured for morning reading, a program fed test input from a file instead of retyped by hand. To re-route output like that, you first need to know what the routes are.

When any program runs, the OS hands it three data channels:

streamnumbernormally connected to
stdin (standard input)0your keyboard
stdout (standard output)1your screen
stderr (standard error)2your screen

Redirection re-plugs these channels:

  • command > file: stdout goes into the file (overwrite)
  • command >> file: stdout appends to the file
  • command < file: stdin comes from the file instead of the keyboard
  • command 2> file: stderr (channel 2!) goes into the file

Normal results and error messages travel on separate channels. That's why you can save one and still see the other.

command(any program)stdin (0): keyboard or < filestdout (1): screen, > or |stderr (2): screen, or 2> file
Input flows in on stdin. Results leave on stdout, errors on stderr, and each can be redirected independently.

Code exercise · bash

Run it. Watch > destroy: two lines go into diary.txt, then a single > wipes them out with one new line.

Code exercise · bash

Errors travel on stream 2. Here cat fails (missing.txt doesn't exist), but 2> catches the complaint in a file, so the script keeps going. Then we read the captured error back.

Throwing output away: /dev/null

/dev/null is a special file the OS provides whose only job is to discard everything written to it. Redirect a stream there when you genuinely don't want it: ls *.txt 2> /dev/null shows what exists and silently drops the complaint if nothing matches. Scripts use this constantly to keep their output clean.

One more combination you'll meet in the wild: command > out.log 2>&1. It sends stdout to the file, and 2>&1 then sends stderr to wherever stream 1 is currently going — so both streams land in the same file. That's how an unattended job's whole story, results and errors together, ends up in a single log.

Code exercise · bash

Run it. ls is asked about two files. The error about missing.txt is discarded into /dev/null, the real result still prints, and the script carries on.

Quiz

What does adding `2> /dev/null` to a command do?

Code exercise · bash

Your turn. Put the numbers 1 to 5 into `five.txt` with seq and >, append the word `done` with >>, then print the last 2 lines with tail. Expected output: ``` 5 done ```