tech katta

Pipes and redirection: stdin, stdout, stderr, >, >>, 2>&1, |, tee and xargs

Lesson 05 of 23 · 5 min readFree

In this lesson

Connect commands together, save output to files, separate errors from normal output, and feed lists of names into other commands.

On this page
  1. Why this matters
  2. Three streams
  3. Redirecting output: > and >>
  4. Redirecting errors: 2> and 2>&1
  5. Redirecting input: <
  6. Pipes: |
  7. tee: save and pass on
  8. xargs: turn a list into arguments
  9. Try it

The real strength of the Linux shell is that small commands can be joined. One command finds lines, another counts them, a third saves the result. This lesson explains the three streams every program has, and the operators that connect them.

Why this matters#

Server work is full of questions like "how many requests failed in the last hour?" or "save everything this deploy script prints so I can read it later". None of these need a special tool. They need grep, wc and a few redirection symbols. Once you understand the three streams, cron jobs, deploy scripts and log commands stop looking like noise.

The examples use the same access.log from the previous lesson.

Three streams#

Every program starts with three open channels, each with a number:

  • stdin (0) is where it reads input. By default that is your keyboard.
  • stdout (1) is where it writes normal output. By default that is your screen.
  • stderr (2) is where it writes errors and warnings. By default that is also your screen.

Because stdout and stderr both go to the screen, they look the same. They are different channels, and you can send them to different places.

Redirecting output: > and >>#

> sends stdout to a file, replacing whatever was there. >> appends to the end of the file.

Shell
echo "deploy started" > deploy.log
echo "step 2" >> deploy.log
cat deploy.log
echo "oops" > deploy.log
cat deploy.log
Text
deploy started
step 2
oops

The last > wiped the two lines and left one. A single > in the wrong place can overwrite a log or a config, so pause before using it on a file you care about. The shell creates the file if it does not exist.

Redirecting errors: 2> and 2>&1#

> only catches stdout. Errors still appear on screen, which is useful, but not in a script that should log everything.

Shell
ls /nonexistent > out.txt
echo "exit=$?"
cat out.txt
Text
ls: cannot access '/nonexistent': No such file or directory
exit=2

The error message was printed to the screen even though we redirected, and out.txt is empty. Use 2> for stderr:

Shell
ls /nonexistent /srv/l5/deploy.log > out.txt 2> err.txt
cat out.txt
cat err.txt
Text
/srv/l5/deploy.log
ls: cannot access '/nonexistent': No such file or directory

Here ls was given one folder that does not exist and one file that does. The success went to out.txt and the failure to err.txt.

To combine both into one file, use 2>&1, which reads "send stream 2 to wherever stream 1 is currently going":

Shell
ls /nonexistent /srv/l5/deploy.log > both.txt 2>&1
cat both.txt
Text
ls: cannot access '/nonexistent': No such file or directory
/srv/l5/deploy.log

In bash you can write &> both.txt for the same thing. To throw output away, send it to /dev/null, a special file that discards everything:

Shell
ls /nonexistent 2>/dev/null

Nothing is printed, though the exit code is still 2. Hiding errors makes problems invisible, so only discard messages you know are harmless.

Order matters#

Redirections are applied left to right. Compare these two:

Shell
ls /nonexistent > x.txt 2>&1
ls /nonexistent 2>&1 > x2.txt

The first prints nothing and x.txt holds the error. The second prints the error on screen, and x2.txt is empty. In the second, 2>&1 ran first, when stdout still pointed at the screen, so stderr was copied to the screen. Only then was stdout moved to the file. Always write > file 2>&1 in that order.

Redirecting input: <#

< feeds a file to stdin. Most commands accept a file name directly, but there is a difference worth seeing:

Shell
wc -l < access.log
wc -l access.log
Text
121
121 access.log

When wc reads a file by name it prints the name too. When it reads stdin it does not know the name, so it prints only the number, which is convenient in scripts.

A here-document, <<, supplies several lines of text inside a script:

Shell
cat <<'EOF' | grep -c nginx
nginx ok
app ok
nginx err
EOF
Text
2

Pipes: |#

A pipe connects the stdout of one command to the stdin of the next. The data flows straight through without a temporary file.

Shell
grep ' 500 ' access.log | wc -l
Text
7

Pipes can be chained as long as you like. Here is a classic: which client addresses made the most requests?

Shell
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head -3
Text
     29 198.51.100.9
     28 203.0.113.25
     24 203.0.113.77

Read it from left to right: take the first field of each line, sort the addresses so equal ones are next to each other, count the repeats, sort the counts from high to low, and show the top three. Each piece does one small thing. Lesson 6 covers cut, sort and uniq properly.

Only stdout goes through a pipe. Errors still reach the screen. To pipe both, write command 2>&1 | next.

A pipeline's exit code#

The exit code of a pipeline is the exit code of its last command, so an early failure can hide.

Shell
false | true
echo "exit=$?"
Text
exit=0

Bash can report the failure instead: set -o pipefail makes the pipeline fail if any step fails. In the test it printed 1 for the same pipeline. Lesson 12 uses this in scripts.

tee: save and pass on#

tee copies stdin to a file and also to stdout. It lets you keep a result and continue the pipeline.

Shell
grep ' 500 ' access.log | tee 500s.txt | wc -l
wc -l 500s.txt
Text
7
7 500s.txt

tee -a appends instead of overwriting. tee is also the standard way to write to a root-owned file from a normal user: echo "setting" | sudo tee /etc/example.conf. A plain sudo echo "setting" > /etc/example.conf fails because the shell, not sudo, opens the file, and the shell is not running as root. (This container runs as root, so we could not reproduce that failure here, but it is the usual behaviour on a normal account.)

xargs: turn a list into arguments#

Many commands expect names as arguments, not as lines of input. xargs reads lines from stdin and builds a command from them.

Shell
find logs -name 'old*.log' | xargs ls -l
Text
-rw-r--r-- 1 root root 0 Dec  2 20:44 logs/old1.log

xargs -n1 runs the command once per item, which is helpful for seeing what happens:

Shell
printf 'one\ntwo\nthree\n' | xargs -n1 echo item
Text
item one
item two
item three

By default xargs splits on spaces, so a file called my file.log is treated as two names, my and file.log:

Text
ls: cannot access 'logs/my': No such file or directory
ls: cannot access 'file.log': No such file or directory

The fix is to separate names with a null character instead, using find -print0 and xargs -0:

Shell
find logs -name 'my*' -print0 | xargs -0 ls
Text
logs/my file.log

Use that pair whenever file names might contain spaces. In many cases find ... -exec does the same job without any splitting problem.

Try it#

  1. Run date > stamp.txt three times and check the file has one line. Then run date >> stamp.txt twice and check it has three.
  2. Run ls /etc /nonexistent so both a success and an error appear. Then save the output to out.txt and the errors to err.txt, and check each file.
  3. Using a log file, find the five most common values of the status code field. Hint: a pipeline of cut, sort, uniq -c and sort -rn.
  4. Run grep ' 404 ' access.log | tee notfound.txt | wc -l and confirm the count matches wc -l notfound.txt.
  5. Create three files, a.tmp, b.tmp and my file.tmp. Delete them with find . -name '*.tmp' -print0 | xargs -0 rm -v, and note what happens if you leave out -print0 and -0.