Learn / Linux / Text Processing
Lesson 10 of 74

Redirection and Pipes

The three standard streams and how to redirect each one: > and >>, 2> and 2>&1, /dev/null, < and here-documents. Then pipes, the heart of the Linux command line: chaining small tools, tee, xargs, command substitution and how pipelines report success or failure.

25 min read Report a problem Hands-on lab included 6-question quiz

Every command has three streams

When a program runs, Linux gives it three open channels, called standard streams, each with a number (a file descriptor):

The three standard streams

0 · stdinstandard input
what the program reads
default: your keyboard
the commande.g. sort, grep, ls
1 · stdoutstandard output: the results
default: your screen
2 · stderrstandard error: error messages
default: your screen

Results and errors both end up on your screen, but they travel on separate streams, so you can send them to different places.

Why separate results from errors? So a script can save its results to a file while you still see problems, or throw away noise without losing results. Redirection is how you choose where each stream goes.

Redirecting output: > and >>

SyntaxEffect
cmd > filestdout into file. The file is created if needed and emptied first if it exists.
cmd >> filestdout to the end of file
bash
echo "Server report" > report.txt
date >> report.txt
uptime >> report.txt
cat report.txt
text
Server report
Tue Nov 24 15:28:22 IST 2026
 15:28:22 up 43 min,  0 user,  load average: 0.41, 0.19, 0.11

The first > created the file, each >> added a line. None of the commands printed anything to the screen: their output went into the file.

Using > when you meant >>. echo "new line" > app.log replaces a whole log with one line, and > /etc/hosts empties it. There's no undo. Safety net: set -o noclobber makes the shell refuse to overwrite existing files with >:

text
$ set -o noclobber; echo x > errors.log
bash: errors.log: cannot overwrite existing file

>| overrides it when you really mean it. Some people put set -o noclobber in their .bashrc.

A neat side effect: > file with no command in front empties a file while keeping it (same owner, permissions, inode). That's the safe way to clear a log that a program has open, as you saw in the inodes lesson. truncate -s 0 file does the same.

Try it · Task 1 of 4

Output into files

Build a small server report file with the hostname, date and uptime.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

> sends a command's output into a file instead of the screen. If the file exists, it's emptied first. >> adds to the end of the file instead. Use > to start a file and >> to keep adding to it.

1. Start a file with >

bash
echo "Server report" > /srv/reports/report.txt
cat /srv/reports/report.txt
PartMeaning
echo "Server report"produces one line of output
> /srv/reports/report.txtsends it into this file (creating it if needed) instead of the screen
text
Server report

Nothing appeared on screen when echo ran: its output went into the file.

2. Add to it with >>

bash
date >> /srv/reports/report.txt
uptime >> /srv/reports/report.txt
cat /srv/reports/report.txt
text
Server report
Tue Nov 24 15:28:22 IST 2026
 15:28:22 up 43 min,  0 user,  load average: 0.41, 0.19, 0.11

Each >> added a line at the end.

3. The trap: > replaces

bash
echo "oops" > /srv/reports/report.txt
cat /srv/reports/report.txt
text
oops

Everything else is gone. One > instead of >> wiped the file, with no warning. On a real server, > /etc/something.conf by mistake destroys a config file. (set -o noclobber makes the shell refuse to overwrite existing files with >.)

2 · Your task

Create /srv/reports/server-report.txt with three lines, in this order:

  1. the output of hostname
  2. the output of date
  3. the output of uptime

Expected result: cat /srv/reports/server-report.txt shows the hostname on line 1, the date on line 2 and the uptime on line 3.

Hint: the commands, explained
text
hostname > /srv/reports/server-report.txt
date >> /srv/reports/server-report.txt
uptime >> /srv/reports/server-report.txt

What each part does

  • hostname > FILE: create the file (or empty it) and write the machine name. One > overwrites.
  • date >> FILE and uptime >> FILE: two > append to the end, keeping what's already there.
First start the lab machine in the terminal panel on the right.

Redirecting errors: 2>, 2>&1 and /dev/null

> is really short for 1>: it only redirects stream 1. Error messages, on stream 2, still reach your screen:

bash
ls /etc/hostname /nope > out.txt
text
ls: cannot access '/nope': No such file or directory

The result (/etc/hostname) went into out.txt, but the error still appeared, because it's on stderr.

SyntaxEffect
cmd 2> err.txterrors into err.txt (no space between 2 and >)
cmd > out.txt 2> err.txtresults and errors into separate files
cmd > all.txt 2>&1both into the same file
cmd &> all.txtthe same, bash shorthand
cmd 2>> err.txtappend errors
cmd 2> /dev/nulldiscard errors
cmd > /dev/null 2>&1discard everything: the command runs silently
bash
ls /etc/hostname /nope > out.txt 2> err.txt
cat out.txt
cat err.txt
text
/etc/hostname
ls: cannot access '/nope': No such file or directory

Each stream landed in its own file, and nothing appeared on screen while ls ran.

Reading 2>&1

2>&1 means "make stream 2 go wherever stream 1 is going right now". The & tells the shell that 1 is a stream number, not a file called "1".

Redirections are applied left to right, so the order matters:

Order matters

cmd > all.txt 2>&1correct
1. stdout → all.txt
2. stderr → where stdout goes now: all.txt
resultboth in the file
cmd 2>&1 > all.txta classic mistake
1. stderr → where stdout goes now: the screen
2. stdout → all.txt
resulterrors still on screen

You'll see > /dev/null 2>&1 at the end of countless cron jobs: "run this, and don't send me any output".

/dev/null: the black hole

/dev/null is a special device file that discards everything written to it (and returns nothing when read). It's perfect for noise you don't need. A normal user searching /etc gets errors for every folder it can't read:

bash
find /etc/ssl /etc/secret-stuff -name "*.cnf"
find /etc/ssl /etc/secret-stuff -name "*.cnf" 2>/dev/null
text
find: '/etc/ssl/private': Permission denied
/etc/ssl/openssl.cnf
find: '/etc/secret-stuff': Permission denied
text
/etc/ssl/openssl.cnf

With errors discarded, only the result is left. Be careful not to hide errors you actually need to see, especially in scripts.

Try it · Task 2 of 4

Keep errors apart

Save a list of config files and the permission errors into two separate files.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Results and errors travel on separate streams: results on stream 1 (stdout), errors on stream 2 (stderr). Plain > only redirects stream 1, which is why error messages still appear on your screen. Redirect stream 2 with 2>.

1. See that > doesn't catch errors

bash
ls /etc/hostname /nope > /tmp/out.txt
cat /tmp/out.txt
text
ls: cannot access '/nope': No such file or directory
/etc/hostname

The error still appeared on screen (it's on stderr), while the result went into the file.

2. Send each stream to its own file

bash
ls /etc/hostname /nope > /tmp/out.txt 2> /tmp/err.txt
cat /tmp/out.txt
cat /tmp/err.txt
PartMeaning
> /tmp/out.txtstream 1 (results) into out.txt
2> /tmp/err.txtstream 2 (errors) into err.txt. No space between 2 and >.
text
/etc/hostname
ls: cannot access '/nope': No such file or directory

Nothing appeared on screen while ls ran. Results and errors went to separate files.

3. Both into one file, or errors into the bin

CommandEffect
cmd > all.txt 2>&1both streams into all.txt. 2>&1 means "send stream 2 wherever stream 1 is going". Order matters: > first, then 2>&1.
cmd &> all.txtthe same, shorter (bash only)
cmd 2> /dev/nullthrow errors away. /dev/null discards anything written to it.

4. A real case: searching as a normal user

The dev user can't read every folder. Watch what happens when it searches for .cnf files:

bash
su - dev -c 'find /etc/ssl /etc/secret-stuff -name "*.cnf"'

What it does: su - dev -c '...' runs the command in quotes as the user dev.

text
find: '/etc/ssl/private': Permission denied
/etc/ssl/openssl.cnf
find: '/etc/secret-stuff': Permission denied

One useful result, buried between two errors. With hundreds of folders, the errors would hide the results completely.

2 · Your task

Run the same search as dev, and save the results to /srv/reports/cnf-files.txt and the errors to /srv/reports/find-errors.txt.

Expected result: cnf-files.txt contains /etc/ssl/openssl.cnf and no "Permission denied" lines; find-errors.txt contains the "Permission denied" lines.

Hint: the commands, explained
text
su - dev -c 'find /etc/ssl /etc/secret-stuff -name "*.cnf"' > /srv/reports/cnf-files.txt 2> /srv/reports/find-errors.txt

What each part does

  • su - dev -c '...': run the command as user dev, who can't read every folder, so some errors happen.
  • > cnf-files.txt: normal output (stdout, stream 1), the found files, goes here.
  • 2> find-errors.txt: errors (stderr, stream 2), such as "Permission denied", go to a separate file.
First start the lab machine in the terminal panel on the right.

Redirecting input: <, here-documents and here-strings

Commands that read input can read it from a file instead of the keyboard:

SyntaxFeeds stdin from
cmd < filea file
cmd << END ... ENDthe lines that follow, up to END (a here-document)
cmd <<< "text"a single string (a here-string)
text
wc -l < /var/log/nginx/access.log     # prints just "400", without the file name

Here-documents are how scripts write multi-line files or feed text to a command:

bash
cat << END > /etc/myapp/app.conf
host=$(hostname)
port=8080
END

Everything between << END and the line END becomes the input; $(hostname) is filled in. Put the marker in quotes (<< 'END') to keep $ signs literally. A here-string is the one-line version:

text
$ tr a-z A-Z <<< "hello pipes"
HELLO PIPES

Pipes: the heart of the command line

The pipe | connects stdout of one command to stdin of the next. No temporary files, and both commands run at the same time, data flowing between them.

text
command1 | command2 | command3

This is what the "small tools that do one thing well" philosophy is for. cut cuts columns, sort sorts, uniq merges duplicates, head takes the top. None of them can find your busiest client alone. Together they can:

bash
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5
text
    147 192.168.1.20
     88 10.0.0.5
     54 10.0.0.9
     40 172.16.4.2
      6 10.0.1.18

How the pipeline works, stage by stage

access.log400 request lines
cut -d' ' -f1keep field 1:
the IP
sortidentical IPs side by side
uniq -cone line per IP, with a count
sort -rnby count, biggest first
head -5the top 5

How to build pipelines: one stage at a time. Run the first command, look at its output, add the next stage, look again. Adding | head while you build keeps the output short.

A few classic one-liners worth recognising:

PipelineAnswers
ps aux | grep nginxis nginx running?
cat app.log | grep ERROR | wc -lhow many errors? (also: grep -c ERROR app.log)
awk '{print $9}' access.log | sort | uniq -chow many responses per status code?
du -sh /var/* | sort -h | tail -5which folders in /var are biggest?
history | grep sshwhich ssh commands did I run?
ls -l | lesspage through a long listing
bash
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c

awk '{print $9}' prints the 9th space-separated field of each line: the HTTP status code. (awk gets its own lesson.)

text
    321 200
     21 301
     27 404
     31 500

321 successful requests, 21 redirects, 27 "not found" and 31 server errors: a status summary in one line.

Only stdout goes through a pipe. Errors still go to your screen. To send errors down the pipe too, use cmd 2>&1 | next (or cmd |& next in bash).

Try it · Task 3 of 4

Pipes

Find the three IP addresses that sent the most requests.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

The pipe | connects two commands: the output of the left one becomes the input of the right one, without any file in between. Each command does one small job, and together they answer questions no single command can. This is the Linux philosophy in action, and it's how engineers analyse logs in seconds.

The web server log has one line per request. Look at the first few lines:

bash
head -n 3 /var/log/nginx/access.log
text
192.168.1.20 - - [24/Nov/2026:10:00:00 +0000] "GET /login HTTP/1.1" 404 7829
192.168.1.20 - - [24/Nov/2026:10:00:01 +0000] "GET /login HTTP/1.1" 404 3311
10.0.0.9 - - [24/Nov/2026:10:00:02 +0000] "GET /login HTTP/1.1" 200 3250

Each line starts with the client IP address. The question: which IPs sent the most requests? Build the answer one pipe at a time, running each version.

1. Take just the IP column

bash
cut -d' ' -f1 /var/log/nginx/access.log | head -3
PartMeaning
cut -d' ' -f1split each line at spaces (-d' ') and keep field 1
| head -3show only the first 3 lines of that, to check it worked
text
192.168.1.20
192.168.1.20
10.0.0.9

Just the IPs, one per request.

2. Count each IP

bash
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | head -5
PartMeaning
sortput identical IPs next to each other
uniq -ccollapse repeated lines into one, with a count in front. It only merges neighbouring duplicates, which is why sort comes first.

3. Biggest counts first, top 5

bash
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5
PartMeaning
sort -rnsort numerically (by the count), in reverse: biggest first
head -5keep the top 5
text
    147 192.168.1.20
     88 10.0.0.5
     54 10.0.0.9
     40 172.16.4.2
      6 10.0.1.18

192.168.1.20 sent 147 of the 400 requests. A single IP with that share of traffic could be a load balancer, a monitoring check, or a misbehaving client worth looking into.

The pipeline, stage by stage

access.log400 lines
cut -f1400 IPs
sortgrouped
uniq -ccount + IP
sort -rnbusiest first
head -3top 3
2 · Your task

Save the top 3 IP addresses with their request counts (biggest first, in the uniq -c format) to /srv/reports/top-ips.txt.

Expected result: /srv/reports/top-ips.txt has 3 lines, starting with the busiest IP and its count.

Hint: the commands, explained
text
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -3 > /srv/reports/top-ips.txt

What each part does

  • cut -d' ' -f1 LOG: split each line on spaces and keep field 1, the client IP.
  • sort | uniq -c: put identical IPs next to each other, then count each group.
  • sort -rn: sort by that count, numbers biggest first. head -3: keep the top 3.
First start the lab machine in the terminal panel on the right.

tee: save and pass on

tee is a T-junction for a pipe: it writes its input into a file and passes it on to stdout.

bash
grep '" 500 ' /var/log/nginx/access.log | tee errors.log | wc -l
text
31

All 31 error lines were saved in errors.log, and wc -l counted them in the same command.

UseExample
keep a log of a long command while watching it./deploy.sh 2>&1 | tee deploy.log
append instead of overwritetee -a file
write to a file that needs rootecho "10.0.0.5 db" | sudo tee -a /etc/hosts

The last one matters. sudo echo "x" > /etc/hosts fails with "Permission denied", because the redirection is done by your shell, which isn't root; only echo runs as root. With | sudo tee, the program writing the file is the one running as root.

xargs: from lines to arguments

Some commands read from stdin (grep, sort, wc). Many others only accept arguments (rm, cp, mkdir, kill). xargs reads lines from stdin and turns them into arguments:

bash
cat to-delete.txt | xargs rm -v

xargs builds and runs rm -v file1 file2 file3 ... from the list.

text
removed '/srv/cleanup/cache-1.tmp'
removed '/srv/cleanup/cache-2.tmp'
removed '/srv/cleanup/cache-3.tmp'
...
OptionEffect
xargs -rdon't run at all if there's no input (avoid rm with no files)
xargs -n 1one argument per command run
xargs -I {} cmd {} ...put each item where {} is: xargs -I {} cp {} /backup/
xargs -P 4run up to 4 commands in parallel
find ... -print0 | xargs -0safe with file names containing spaces

Preview what it will do by putting echo in front: cat list.txt | xargs echo rm.

Try it · Task 4 of 4

tee and xargs

Save every failed request while counting them, then delete the listed temporary files.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Two helpers complete the toolbox:

  • tee is a T-junction in a pipe: it writes what passes through it into a file and passes it on, so you can save and keep working (or keep watching) at the same time.
  • xargs turns lines of input into arguments for a command. Many commands, like rm, don't read a list from a pipe; they need file names as arguments. xargs bridges that gap.

1. Save and count at once with tee

bash
grep '" 500 ' /var/log/nginx/access.log | tee /srv/reports/errors.log | wc -l
PartMeaning
grep '" 500 'keep only requests that returned status 500 (server error)
tee /srv/reports/errors.logwrite those lines into the file and pass them on down the pipe
wc -lcount them
text
31

31 failed requests, and all 31 lines are now saved in errors.log for the developers. Without tee you'd need two commands. tee -a appends instead of replacing.

A very common use: writing to a root-owned file when using sudo. sudo echo x > /etc/file fails (the redirection happens in your shell, not as root), but echo x | sudo tee /etc/file works.

2. Turn a list into arguments with xargs

There's a list of files to delete:

bash
cat /srv/cleanup/to-delete.txt
text
/srv/cleanup/cache-1.tmp
/srv/cleanup/cache-2.tmp
...
bash
cat /srv/cleanup/to-delete.txt | xargs rm -v

What it does: xargs reads the six paths and runs rm -v /srv/cleanup/cache-1.tmp /srv/cleanup/cache-2.tmp ... with all of them as arguments.

text
removed '/srv/cleanup/cache-1.tmp'
removed '/srv/cleanup/cache-2.tmp'
removed '/srv/cleanup/cache-3.tmp'
removed '/srv/cleanup/cache-4.tmp'
removed '/srv/cleanup/cache-5.tmp'
removed '/srv/cleanup/cache-6.tmp'

Preview first with cat, or run xargs echo rm to see the command it would build. xargs -r does nothing if the list is empty, which keeps scripts safe.

2 · Your task
  1. Save every request with status 500 to /srv/reports/errors.log, using tee so you also see how many there are.
  2. Delete all the files listed in /srv/cleanup/to-delete.txt using xargs. Keep keep.txt.

Expected result: errors.log contains all the 500 lines, the .tmp files are gone, and keep.txt is still there.

Hint: the commands, explained
text
grep '" 500 ' /var/log/nginx/access.log | tee /srv/reports/errors.log | wc -l
cat /srv/cleanup/to-delete.txt | xargs rm

What each part does

  • grep '" 500 ': lines where the status code after the closing quote is 500.
  • tee FILE: save a copy of what passes through into a file and pass it on down the pipe. wc -l counts the lines.
  • cat LIST | xargs rm: xargs turns each line of input into arguments, so this runs rm file1 file2 ....
First start the lab machine in the terminal panel on the right.

Command substitution: $( )

$(command) runs a command and puts its output right into another command line:

bash
echo "Today is $(date +%A) and this host has $(nproc) CPUs"
text
Today is Tuesday and this host has 2 CPUs

You've already used it: kill $(pgrep shop-worker), cp app.conf app.conf.$(date +%F) (a dated backup), cd $(dirname /path/to/file). The older backtick syntax `date` does the same, but $( ) is easier to read and can be nested.

Did the pipeline succeed?

The exit code of a pipeline is the exit code of its last command. Earlier failures are hidden:

text
$ false | true; echo "exit: $?"
exit: 0
$ set -o pipefail; false | true; echo "with pipefail: $?"
with pipefail: 1

false failed, but because true succeeded, the whole pipeline reported success. With set -o pipefail, a pipeline fails if any stage fails. That's why serious bash scripts start with set -euo pipefail (you'll meet this again in the scripting module).

"What do 0, 1 and 2 mean in redirection?" The standard streams: 0 stdin, 1 stdout, 2 stderr. 2> redirects errors, 2>&1 sends errors to the same place as output.

"What does > /dev/null 2>&1 do?" Discards both output and errors, typically at the end of cron jobs.

"How do you write to a root-owned file with sudo using redirection?" echo "line" | sudo tee -a /etc/file, because the shell's own redirection doesn't run as root.

"What's the difference between a pipe and redirection?" Redirection connects a stream to a file; a pipe connects one command's stdout to another command's stdin.

Summary

  • Streams: 0 stdin, 1 stdout (results), 2 stderr (errors).
  • > replaces, >> appends; > file alone empties a file safely.
  • 2> file saves errors, 2>/dev/null discards them, > file 2>&1 (in that order) or &> file saves both.
  • < file feeds input; here-documents (<< END) and here-strings (<<< "text") feed text.
  • | chains commands; build pipelines one stage at a time. Only stdout goes through the pipe.
  • tee saves and passes on (| sudo tee for root files); xargs turns lines into arguments; $(cmd) inserts a command's output.
  • A pipeline's exit code is its last command's, unless set -o pipefail.
Check your understanding

Quick quiz

Feedback