Pipes and redirection: stdin, stdout, stderr, >, >>, 2>&1, |, tee and xargs
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
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.
echo "deploy started" > deploy.log
echo "step 2" >> deploy.log
cat deploy.log
echo "oops" > deploy.log
cat deploy.logdeploy started
step 2
oopsThe 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.
ls /nonexistent > out.txt
echo "exit=$?"
cat out.txtls: cannot access '/nonexistent': No such file or directory
exit=2The error message was printed to the screen even though we redirected, and out.txt is empty. Use 2> for stderr:
ls /nonexistent /srv/l5/deploy.log > out.txt 2> err.txt
cat out.txt
cat err.txt/srv/l5/deploy.log
ls: cannot access '/nonexistent': No such file or directoryHere 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":
ls /nonexistent /srv/l5/deploy.log > both.txt 2>&1
cat both.txtls: cannot access '/nonexistent': No such file or directory
/srv/l5/deploy.logIn 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:
ls /nonexistent 2>/dev/nullNothing 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:
ls /nonexistent > x.txt 2>&1
ls /nonexistent 2>&1 > x2.txtThe 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:
wc -l < access.log
wc -l access.log121
121 access.logWhen 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:
cat <<'EOF' | grep -c nginx
nginx ok
app ok
nginx err
EOF2Pipes: |#
A pipe connects the stdout of one command to the stdin of the next. The data flows straight through without a temporary file.
grep ' 500 ' access.log | wc -l7Pipes can be chained as long as you like. Here is a classic: which client addresses made the most requests?
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head -3 29 198.51.100.9
28 203.0.113.25
24 203.0.113.77Read 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.
false | true
echo "exit=$?"exit=0Bash 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.
grep ' 500 ' access.log | tee 500s.txt | wc -l
wc -l 500s.txt7
7 500s.txttee -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.
find logs -name 'old*.log' | xargs ls -l-rw-r--r-- 1 root root 0 Dec 2 20:44 logs/old1.logxargs -n1 runs the command once per item, which is helpful for seeing what happens:
printf 'one\ntwo\nthree\n' | xargs -n1 echo itemitem one
item two
item threeBy default xargs splits on spaces, so a file called my file.log is treated as two names, my and file.log:
ls: cannot access 'logs/my': No such file or directory
ls: cannot access 'file.log': No such file or directoryThe fix is to separate names with a null character instead, using find -print0 and xargs -0:
find logs -name 'my*' -print0 | xargs -0 lslogs/my file.logUse that pair whenever file names might contain spaces. In many cases find ... -exec does the same job without any splitting problem.
Try it#
- Run
date > stamp.txtthree times and check the file has one line. Then rundate >> stamp.txttwice and check it has three. - Run
ls /etc /nonexistentso both a success and an error appear. Then save the output toout.txtand the errors toerr.txt, and check each file. - Using a log file, find the five most common values of the status code field. Hint: a pipeline of
cut,sort,uniq -candsort -rn. - Run
grep ' 404 ' access.log | tee notfound.txt | wc -land confirm the count matcheswc -l notfound.txt. - Create three files,
a.tmp,b.tmpandmy file.tmp. Delete them withfind . -name '*.tmp' -print0 | xargs -0 rm -v, and note what happens if you leave out-print0and-0.
Sign in to keep track of the lessons you finish.