Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Redirections and pipes on Linux

By updated

Improve this page

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:

StreamNumberNameRole
Standard input0stdinWhat the command reads (keyboard by default)
Standard output1stdoutThe normal result (screen by default)
Standard error2stderrError 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:

Terminal window
ls /etc > list.txt

The file list.txt now contains the list of the files in /etc. Nothing shows on the screen.

Check:

Terminal window
head -n 5 list.txt

>>: append at the end

The >> operator appends at the end of the file without overwriting the existing contents:

Terminal window
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.

Terminal window
echo "important data" > report.txt
command-that-does-not-exist > report.txt
bash: command-that-does-not-exist: command not found

The command never ran, it exits with an error (code 127), and yet:

Terminal window
stat -c %s report.txt
0

The 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:

Terminal window
echo "nameserver 1.1.1.1" > /tmp/resolv-test.conf

How 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:

Terminal window
find /etc -name "*.conf" 2> errors.log

The 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:

Terminal window
find / -name "sshd_config" 2>/dev/null

The "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:

Terminal window
find / -name "*.log" > all.log 2>&1

2>&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:

Terminal window
command 2>&1 > all.log

Here, 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:

FormFile contents
> all.log 2>&175 bytes, both streams
2>&1 > all.log16 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

Terminal window
ls /etc | head -n 5

ls lists the files, and the pipe sends that list to head, which only shows the first 5 lines.

Chain several pipes

Terminal window
cat /etc/passwd | cut -d: -f1 | sort
  1. cat /etc/passwd prints the file
  2. cut -d: -f1 extracts the first field (the user name), using : as the delimiter
  3. sort sorts alphabetically

The result: the sorted list of every user on the system.

Count results

Terminal window
ls /etc | wc -l

wc -l counts the number of lines: here, the number of files and directories in /etc.

Filter with grep

Terminal window
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.

Terminal window
missing-command | wc -l
echo $?
0

missing-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:

Terminal window
missing-command | wc -l
echo "${PIPESTATUS[@]}"
127 0

The 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:

Terminal window
ls /etc | tee list.txt

The result shows on the screen and is saved in list.txt.

To append to the file instead of overwriting it:

Terminal window
ls /var | tee -a list.txt

Which 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.

OperatorRoleExample
>Redirects stdout to a file (overwrites)ls > file.txt
>>Redirects stdout to a file (appends)echo "end" >> file.txt
2>Redirects stderr to a filefind / -name x 2> err.log
2>/dev/nullIgnores errorsfind / -name x 2>/dev/null
> f 2>&1Redirects stdout + stderrcmd > all.log 2>&1
|Pipe: output of one command → input of the nextls | head
teeShows and saves at the same timels | 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.

ProblemLikely causeFix
> overwrote my file> always overwritesUse >> to append
My file is empty although the command failed> empties the file before running the commandWrite to a new file, then replace once the result is checked
The pipe gives nothingThe first command produces no outputTest the first command on its own
The pipeline "succeeds" although a command failedThe exit code is that of the last commandRead ${PIPESTATUS[@]}, or set -o pipefail in a script
Part of the output is missing from the fileWritten as > f 2> f: two openings, two cursorsUse > 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 resultstdout and stderr mixed on screenAdd 2>/dev/null
tee: command not foundVery rare, coreutils package missingsudo 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[@]} or set -o pipefail to see the others.
  • 2>/dev/null removes the errors, essential with find run without sudo.
  • To merge the streams, > f 2>&1, never > f 2> f, which destroys part of them. The order matters.
  • sudo cmd > /protected-file fails when your account cannot write to the target: the redirection is done by your shell, not by sudo. Use | sudo tee.
  • tee is 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

6 questions
6 min
70% to pass

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