Redirection, stdout and stderr, and pipes
You capture a backup script’s normal output and its errors separately, join them, throw away the noise into /dev/null, feed input from a file, use a here-doc and a here-string, write to the screen and a file at once with tee, prevent accidental overwrites with noclobber; at the end you run the script silently and split its logs. The numbers of errors and records differ in every lab.
Level 101 · 45 min
Every morning the nightly backup script leaves a messy output on the screen: successful copies and errors mixed together. Daniel wants you to separate them and collect the errors in their own file.
Every command has three standard channels: stdin (0, input, the keyboard by default), stdout (1, normal output, the screen by default) and stderr (2, error output, also the screen by default). Since both outputs go to the same screen they look mixed, but they are separate pipes and can be redirected separately.
Analogy: a factory has two exits, one for products and one for scrap. Both pour into the same yard, so it looks mixed. Redirection means putting a separate lorry at each exit. The figure shows the three channels.
What you will do in this lesson
- Capture only the normal output: >
- Errors into their own file: 2>
- Both together: 2>&1 and &>
- The black hole: /dev/null
- Input from a file: <
- Here-doc and here-string
- To the screen and a file: tee
- Prevent accidental overwrites: noclobber
- A silent run
- Short quiz
Skills you will earn
- Redirecting output to a file with > and >>
- Redirecting error output (2>)
- Redirecting both outputs (2>&1, &>)
- Discarding output (/dev/null)
- Feeding input from a file (<)
- Using here-docs and here-strings
- Writing to screen and file at once (tee)
- Preventing accidental overwrites (noclobber)
- Writing a short, precise finding
← Short task: tidy a messy project folder and find the missing file · Linux fundamentals · Filtering and counting: grep, sort, uniq, wc, cut →
Start for free