On Linux, every command produces text as output, and that text can be sent somewhere other than the screen. To a file, to another command, or even into nothingness (/dev/null). This mechanism is called redirection, and it is one of the most powerful concepts of the shell. Combined with the pipe (|), it lets you chain simple commands to carry out complex tasks.
What you will learn
- Redirect a command's output to a file with
>and>> - Tell apart standard output and error output
- Chain commands with the pipe
| - Hide errors with
/dev/null - Show and save at the same time with
tee - Avoid the four traps that lose data or lie about the result
What are the three streams of the shell?
Before redirecting anything, you need to understand that every command uses three streams:
| Stream | Number | Name | Role |
|---|---|---|---|
| Standard input | 0 | stdin | What the command reads (keyboard by default) |
| Standard output | 1 | stdout | The normal result (screen by default) |
| Standard error | 2 | stderr | Error messages (screen by default) |
By default, stdout and stderr both reach the screen. Redirections let you send them elsewhere.
How do you redirect output to a file?
A process writes by default to two distinct streams, the standard output and the error output. A redirection diverts the first one to a file; the second keeps showing on the screen as long as you do not handle it separately.
>: write (overwriting)
The > operator sends standard output to a file. If the file exists, it is overwritten:
ls /etc > list.txtThe file list.txt now contains the list of the files in /etc. Nothing shows on the screen.
Check:
head -n 5 list.txt>>: append at the end
The >> operator appends at the end of the file without overwriting the existing contents:
echo "--- End of report ---" >> list.txt> empties the file even when the command fails
Here is the trap that costs beginners the most, and it is not obvious: it is the shell that sets up the redirection, before running the command. The file is therefore emptied first, whatever happens next.
echo "important data" > report.txtcommand-that-does-not-exist > report.txtbash: command-that-does-not-exist: command not foundThe command never ran, it exits with an error (code 127), and yet:
stat -c %s report.txt0The file is zero bytes. A simple typo in a command name is therefore enough to wipe an existing file. The protective reflex is to write to a new file first, then replace the old one once the result is checked.
Create a file from scratch
Redirecting echo is a simple way to create a small file:
echo "nameserver 1.1.1.1" > /tmp/resolv-test.confHow do you redirect errors?
Each stream carries a numeric descriptor: 1 for standard output, 2 for errors. That is the number you place in front of the chevron to choose which stream to divert, > alone being a shortcut for 1>.
2>: redirect stderr
To send the error messages to a separate file:
find /etc -name "*.conf" 2> errors.logThe normal results show on the screen. The "Permission denied" errors go to errors.log.
2>/dev/null: ignore errors
/dev/null is a special file that swallows everything you send it. It is the "black hole" of Linux:
find / -name "sshd_config" 2>/dev/nullThe "Permission denied" errors disappear, and only the useful results show up.
Redirect stdout and stderr together
To send everything (result + errors) to the same file:
find / -name "*.log" > all.log 2>&12>&1 means "send stream 2 (stderr) where stream 1 (stdout) goes".
The order matters, and it is not intuitive. The shell reads redirections from
left to right. In > all.log 2>&1, stdout first goes to the file, then stderr
is sent "to the same place as stdout", so to the file as well. Swap them and
you no longer get the same thing:
command 2>&1 > all.logHere, stderr is sent "where stdout goes" while stdout still points to the screen. It therefore goes to the screen, and only stdout ends up in the file. Measured on a command producing 16 bytes on stdout and 59 on stderr:
| Form | File contents |
|---|---|
> all.log 2>&1 | 75 bytes, both streams |
2>&1 > all.log | 16 bytes, stdout only |
Remember the correct form: the stdout redirection comes first.
How does the pipe | chain commands?
The pipe (|) connects the output of one command to the input of the next. It is the basis of the Unix philosophy: simple tools combined with each other.
Basic example
ls /etc | head -n 5ls lists the files, and the pipe sends that list to head, which only shows the first 5 lines.
Chain several pipes
cat /etc/passwd | cut -d: -f1 | sortcat /etc/passwdprints the filecut -d: -f1extracts the first field (the user name), using:as the delimitersortsorts alphabetically
The result: the sorted list of every user on the system.
Count results
ls /etc | wc -lwc -l counts the number of lines: here, the number of files and directories in /etc.
Filter with grep
ps aux | grep "sshd"ps aux lists every process, and grep keeps only those containing "sshd".
A successful pipe can hide a failed command
As soon as you put a pipe in a script, this detail will catch up with you: the exit code of a pipeline is that of its last command, not that of the first one that failed.
missing-command | wc -lecho $?0missing-command does not exist, but wc -l counted zero lines without
complaining, and its code is the one that comes out. A script that tests $?
concludes that everything went fine.
Bash still keeps track of each link in the PIPESTATUS array:
missing-command | wc -lecho "${PIPESTATUS[@]}"127 0The 127 is there. In a script, the simplest fix is to ask the shell to
propagate the failure with set -o pipefail, which then brings out 127.
tee: show and save at the same time
By default, a > redirection sends everything to the file and nothing to the screen. If you want both:
ls /etc | tee list.txtThe result shows on the screen and is saved in list.txt.
To append to the file instead of overwriting it:
ls /var | tee -a list.txtWhich operator does what?
The seven operators below cover almost every redirection you will write. Read the Role column first, then check the Example column when you type the command.
| Operator | Role | Example |
|---|---|---|
> | Redirects stdout to a file (overwrites) | ls > file.txt |
>> | Redirects stdout to a file (appends) | echo "end" >> file.txt |
2> | Redirects stderr to a file | find / -name x 2> err.log |
2>/dev/null | Ignores errors | find / -name x 2>/dev/null |
> f 2>&1 | Redirects stdout + stderr | cmd > all.log 2>&1 |
| | Pipe: output of one command → input of the next | ls | head |
tee | Shows and saves at the same time | ls | tee file.txt |
Troubleshooting
Redirection mistakes are silent most of the time: a file comes out empty or incomplete, and no message says why. The table sorts them by the symptom you notice.
| Problem | Likely cause | Fix |
|---|---|---|
> overwrote my file | > always overwrites | Use >> to append |
| My file is empty although the command failed | > empties the file before running the command | Write to a new file, then replace once the result is checked |
| The pipe gives nothing | The first command produces no output | Test the first command on its own |
| The pipeline "succeeds" although a command failed | The exit code is that of the last command | Read ${PIPESTATUS[@]}, or set -o pipefail in a script |
| Part of the output is missing from the file | Written as > f 2> f: two openings, two cursors | Use > f 2>&1 |
Permission denied with > | Your account cannot write to the target file (or to its directory, if the file does not exist yet) | See the box below: sudo alone is not enough |
| Errors clutter the result | stdout and stderr mixed on screen | Add 2>/dev/null |
tee: command not found | Very rare, coreutils package missing | sudo dnf install coreutils (RHEL/AlmaLinux) or sudo apt install coreutils (Debian/Ubuntu) |
Put it into practice
The difference between > and 2> only becomes a reflex once you have produced the expected files yourself. This lab asks you to separate stdout and stderr, to merge them when useful, then to chain commands with a pipe to build exact artefacts, checked down to the byte.
Key points
>overwrites,>>appends: it is the most important difference.>empties the file before running the command: a typo is enough to wipe an existing file.|(pipe) is the glue of the command line: it connects tools together.- The exit code of a pipeline is that of the last command:
${PIPESTATUS[@]}orset -o pipefailto see the others. 2>/dev/nullremoves the errors, essential withfindrun withoutsudo.- To merge the streams,
> f 2>&1, never> f 2> f, which destroys part of them. The order matters. sudo cmd > /protected-filefails when your account cannot write to the target: the redirection is done by your shell, not bysudo. Use| sudo tee.teeis the compromise: show on screen and keep a trace in a file.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Archive and compress files on Linux
A new full quiz with random questions
Work again only on the questions you missed