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.
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
what the program reads
default: your keyboard
sort, grep, lsdefault: your screen
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 >>
| Syntax | Effect |
|---|---|
cmd > file | stdout into file. The file is created if needed and emptied first if it exists. |
cmd >> file | stdout to the end of file |
echo "Server report" > report.txt
date >> report.txt
uptime >> report.txt
cat report.txtServer report
Tue Nov 24 15:28:22 IST 2026
15:28:22 up 43 min, 0 user, load average: 0.41, 0.19, 0.11The 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 >:
$ 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.
Output into files
Build a small server report file with the hostname, date and uptime.
> 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 >
echo "Server report" > /srv/reports/report.txt
cat /srv/reports/report.txt| Part | Meaning |
|---|---|
echo "Server report" | produces one line of output |
> /srv/reports/report.txt | sends it into this file (creating it if needed) instead of the screen |
Server reportNothing appeared on screen when echo ran: its output went into the file.
2. Add to it with >>
date >> /srv/reports/report.txt
uptime >> /srv/reports/report.txt
cat /srv/reports/report.txtServer report
Tue Nov 24 15:28:22 IST 2026
15:28:22 up 43 min, 0 user, load average: 0.41, 0.19, 0.11Each >> added a line at the end.
3. The trap: > replaces
echo "oops" > /srv/reports/report.txt
cat /srv/reports/report.txtoopsEverything 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 >.)
Create /srv/reports/server-report.txt with three lines, in this order:
- the output of
hostname - the output of
date - 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
hostname > /srv/reports/server-report.txt
date >> /srv/reports/server-report.txt
uptime >> /srv/reports/server-report.txtWhat each part does
hostname > FILE: create the file (or empty it) and write the machine name. One>overwrites.date >> FILEanduptime >> FILE: two>append to the end, keeping what's already there.
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:
ls /etc/hostname /nope > out.txtls: cannot access '/nope': No such file or directoryThe result (/etc/hostname) went into out.txt, but the error still appeared, because it's on stderr.
| Syntax | Effect |
|---|---|
cmd 2> err.txt | errors into err.txt (no space between 2 and >) |
cmd > out.txt 2> err.txt | results and errors into separate files |
cmd > all.txt 2>&1 | both into the same file |
cmd &> all.txt | the same, bash shorthand |
cmd 2>> err.txt | append errors |
cmd 2> /dev/null | discard errors |
cmd > /dev/null 2>&1 | discard everything: the command runs silently |
ls /etc/hostname /nope > out.txt 2> err.txt
cat out.txt
cat err.txt/etc/hostname
ls: cannot access '/nope': No such file or directoryEach 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
2. stderr → where stdout goes now: all.txt
2. stdout → all.txt
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:
find /etc/ssl /etc/secret-stuff -name "*.cnf"
find /etc/ssl /etc/secret-stuff -name "*.cnf" 2>/dev/nullfind: '/etc/ssl/private': Permission denied
/etc/ssl/openssl.cnf
find: '/etc/secret-stuff': Permission denied/etc/ssl/openssl.cnfWith errors discarded, only the result is left. Be careful not to hide errors you actually need to see, especially in scripts.
Keep errors apart
Save a list of config files and the permission errors into two separate files.
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
ls /etc/hostname /nope > /tmp/out.txt
cat /tmp/out.txtls: cannot access '/nope': No such file or directory
/etc/hostnameThe error still appeared on screen (it's on stderr), while the result went into the file.
2. Send each stream to its own file
ls /etc/hostname /nope > /tmp/out.txt 2> /tmp/err.txt
cat /tmp/out.txt
cat /tmp/err.txt| Part | Meaning |
|---|---|
> /tmp/out.txt | stream 1 (results) into out.txt |
2> /tmp/err.txt | stream 2 (errors) into err.txt. No space between 2 and >. |
/etc/hostname
ls: cannot access '/nope': No such file or directoryNothing appeared on screen while ls ran. Results and errors went to separate files.
3. Both into one file, or errors into the bin
| Command | Effect |
|---|---|
cmd > all.txt 2>&1 | both streams into all.txt. 2>&1 means "send stream 2 wherever stream 1 is going". Order matters: > first, then 2>&1. |
cmd &> all.txt | the same, shorter (bash only) |
cmd 2> /dev/null | throw 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:
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.
find: '/etc/ssl/private': Permission denied
/etc/ssl/openssl.cnf
find: '/etc/secret-stuff': Permission deniedOne useful result, buried between two errors. With hundreds of folders, the errors would hide the results completely.
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
su - dev -c 'find /etc/ssl /etc/secret-stuff -name "*.cnf"' > /srv/reports/cnf-files.txt 2> /srv/reports/find-errors.txtWhat 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.
Redirecting input: <, here-documents and here-strings
Commands that read input can read it from a file instead of the keyboard:
| Syntax | Feeds stdin from |
|---|---|
cmd < file | a file |
cmd << END ... END | the lines that follow, up to END (a here-document) |
cmd <<< "text" | a single string (a here-string) |
wc -l < /var/log/nginx/access.log # prints just "400", without the file nameHere-documents are how scripts write multi-line files or feed text to a command:
cat << END > /etc/myapp/app.conf
host=$(hostname)
port=8080
ENDEverything 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:
$ tr a-z A-Z <<< "hello pipes"
HELLO PIPESPipes: 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.
command1 | command2 | command3This 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:
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5 147 192.168.1.20
88 10.0.0.5
54 10.0.0.9
40 172.16.4.2
6 10.0.1.18How the pipeline works, stage by stage
the IP
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:
| Pipeline | Answers |
|---|---|
ps aux | grep nginx | is nginx running? |
cat app.log | grep ERROR | wc -l | how many errors? (also: grep -c ERROR app.log) |
awk '{print $9}' access.log | sort | uniq -c | how many responses per status code? |
du -sh /var/* | sort -h | tail -5 | which folders in /var are biggest? |
history | grep ssh | which ssh commands did I run? |
ls -l | less | page through a long listing |
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -cawk '{print $9}' prints the 9th space-separated field of each line: the HTTP status code. (awk gets its own lesson.)
321 200
21 301
27 404
31 500321 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).
Pipes
Find the three IP addresses that sent the most requests.
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:
head -n 3 /var/log/nginx/access.log192.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 3250Each 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
cut -d' ' -f1 /var/log/nginx/access.log | head -3| Part | Meaning |
|---|---|
cut -d' ' -f1 | split each line at spaces (-d' ') and keep field 1 |
| head -3 | show only the first 3 lines of that, to check it worked |
192.168.1.20
192.168.1.20
10.0.0.9Just the IPs, one per request.
2. Count each IP
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | head -5| Part | Meaning |
|---|---|
sort | put identical IPs next to each other |
uniq -c | collapse 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
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5| Part | Meaning |
|---|---|
sort -rn | sort numerically (by the count), in reverse: biggest first |
head -5 | keep the top 5 |
147 192.168.1.20
88 10.0.0.5
54 10.0.0.9
40 172.16.4.2
6 10.0.1.18192.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
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
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -3 > /srv/reports/top-ips.txtWhat 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.
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.
grep '" 500 ' /var/log/nginx/access.log | tee errors.log | wc -l31All 31 error lines were saved in errors.log, and wc -l counted them in the same command.
| Use | Example |
|---|---|
| keep a log of a long command while watching it | ./deploy.sh 2>&1 | tee deploy.log |
| append instead of overwrite | tee -a file |
| write to a file that needs root | echo "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:
cat to-delete.txt | xargs rm -vxargs builds and runs rm -v file1 file2 file3 ... from the list.
removed '/srv/cleanup/cache-1.tmp'
removed '/srv/cleanup/cache-2.tmp'
removed '/srv/cleanup/cache-3.tmp'
...| Option | Effect |
|---|---|
xargs -r | don't run at all if there's no input (avoid rm with no files) |
xargs -n 1 | one argument per command run |
xargs -I {} cmd {} ... | put each item where {} is: xargs -I {} cp {} /backup/ |
xargs -P 4 | run up to 4 commands in parallel |
find ... -print0 | xargs -0 | safe with file names containing spaces |
Preview what it will do by putting echo in front: cat list.txt | xargs echo rm.
tee and xargs
Save every failed request while counting them, then delete the listed temporary files.
Two helpers complete the toolbox:
teeis 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.xargsturns lines of input into arguments for a command. Many commands, likerm, don't read a list from a pipe; they need file names as arguments.xargsbridges that gap.
1. Save and count at once with tee
grep '" 500 ' /var/log/nginx/access.log | tee /srv/reports/errors.log | wc -l| Part | Meaning |
|---|---|
grep '" 500 ' | keep only requests that returned status 500 (server error) |
tee /srv/reports/errors.log | write those lines into the file and pass them on down the pipe |
wc -l | count them |
3131 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:
cat /srv/cleanup/to-delete.txt/srv/cleanup/cache-1.tmp
/srv/cleanup/cache-2.tmp
...cat /srv/cleanup/to-delete.txt | xargs rm -vWhat 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.
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.
- Save every request with status 500 to
/srv/reports/errors.log, usingteeso you also see how many there are. - Delete all the files listed in
/srv/cleanup/to-delete.txtusingxargs. Keepkeep.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
grep '" 500 ' /var/log/nginx/access.log | tee /srv/reports/errors.log | wc -l
cat /srv/cleanup/to-delete.txt | xargs rmWhat 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 -lcounts the lines.cat LIST | xargs rm:xargsturns each line of input into arguments, so this runsrm file1 file2 ....
Command substitution: $( )
$(command) runs a command and puts its output right into another command line:
echo "Today is $(date +%A) and this host has $(nproc) CPUs"Today is Tuesday and this host has 2 CPUsYou'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:
$ false | true; echo "exit: $?"
exit: 0
$ set -o pipefail; false | true; echo "with pipefail: $?"
with pipefail: 1false 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;> filealone empties a file safely.2> filesaves errors,2>/dev/nulldiscards them,> file 2>&1(in that order) or&> filesaves both.< filefeeds 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.teesaves and passes on (| sudo teefor root files);xargsturns lines into arguments;$(cmd)inserts a command's output.- A pipeline's exit code is its last command's, unless
set -o pipefail.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.