Part 1 · Basics · Lesson 06 · 40 minutes
Join commands with pipes, redirects and tee
- Send the output and the errors of a command to files, and read a file as input
- Join commands with pipes, and run one after another with && and ||
- Save a result and see it at the same time with tee
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team lead wants a report on the errors in a service log. She says: "I want to see the number on the screen, I want the lines saved in a file for the ticket, and I want the errors of your commands in a separate file, so that I can see what went wrong. And do not start the next step if the check before it failed." The log has nine lines. Your job is to build the commands that do this.
Recall
Why must you run "sort" before "uniq -c"?
uniq merges only lines that are next to each other. sort puts equal lines together, so uniq -c can count each group.
What does "grep -c" print, and how is it different from plain "grep"?
It prints the number of matching lines, not the lines themselves.
The idea
Every program that you run has three connections to the world. They are called standard streams, and each has a number.
- Keyboard → ls: stdin (0): input; ls does not use it
- ls → Screen: stdout (1): log.txt, the result
- ls → err.txt: stderr (2): the complaint, with 2>
By default stdin is your keyboard, and stdout and stderr are both your screen. The shell can connect each stream to a file or to another program. This table shows how.
| Symbol | What it does |
|---|---|
> | Send stdout to a file. It replaces the file. |
>> | Add stdout to the end of a file. |
2> | Send stderr to a file. |
2>&1 | Send stderr to the place where stdout goes now. |
< | Read stdin from a file. |
| | The pipe: send stdout of one command into stdin of the next. |
&& | Run the next command only if the first one succeeded. |
|| | Run the next command only if the first one failed. |
Every command ends with an exit status: 0 means success, and any other number means failure. && and || read it.
Worked example
1. See the two output streams
Make a lab folder with a file and run ls on a name that exists and one that does not. ls (list) prints the file name on stdout and the complaint on stderr. Both go to the screen, so you cannot tell them apart.
mkdir -p ~/krlab/linux-basics/streams && cd ~/krlab/linux-basics/streams
echo "first" > log.txt
ls log.txt missingls: cannot access 'missing': No such file or directory
log.txtThe error comes first because ls checks every name before it prints.
2. Send the output to a file
> writes stdout into a file and replaces what the file held. >> adds to the end. cat prints the file.
echo "second" > log.txt
cat log.txt
echo "third" >> log.txt
cat log.txtsecond
second
thirdThe first line, first, is gone. Check the file name before you use >.
3. Send the errors to a file
2> writes stderr into a file. Only the file name stays on the screen. 2>&1 joins stderr to stdout, so that one file gets both. The order of the two redirects matters: 2>&1 copies the place where stdout goes at that moment.
First, only the errors go to a file. The command prints log.txt on the screen, and err.txt holds the complaint.
ls log.txt missing 2> err.txtlog.txtcat err.txtls: cannot access 'missing': No such file or directorySecond, both streams go to one file. The screen stays empty, and both.txt holds both lines.
ls log.txt missing > both.txt 2>&1
cat both.txtls: cannot access 'missing': No such file or directory
log.txtThird, the two redirects are in the other order. 2>&1 ran first, while stdout still pointed to the screen, so the error stayed on the screen. Only log.txt went into the file.
ls log.txt missing 2>&1 > only.txtls: cannot access 'missing': No such file or directorycat only.txtlog.txt/dev/null is a file that throws away what you write to it: 2> /dev/null hides the errors.
4. Read from a file and use the pipe
< gives a file to a command as its stdin. wc -l counts lines, and with < it does not print the file name. A pipe sends stdout, but not stderr, to the next command: the error below still shows on the screen and wc counts 0 lines. 2>&1 | (or |& in bash) sends both.
wc -l < log.txt
ls missing | wc -l
ls missing 2>&1 | wc -l2
ls: cannot access 'missing': No such file or directory
0
15. Run commands in order with && and ||
$? holds the exit status of the last command. grep -q (quiet) prints nothing and only sets the status: 0 if a line matches, 1 if none does. ; runs the next command whatever the status is.
ls log.txt; echo "status $?"
ls missing; echo "status $?"
grep -q second log.txt && echo found || echo missing
grep -q CRITICAL log.txt && echo found || echo missing
cd missing && echo enteredlog.txt
status 0
ls: cannot access 'missing': No such file or directory
status 2
found
missing
bash: cd: missing: No such file or directoryThe last line shows the use: echo entered did not run, because cd failed. One trap: in A && B || C, the command C also runs when B fails. Use it for a short test, not for a long sequence.
6. Write to the screen and to a file with tee
tee reads stdin and writes it twice: to stdout and to each file that you name. It replaces the file, as > does. tee -a (append) adds to the end.
echo hello | tee out.txt
echo again | tee out.txt
echo more | tee -a out.txt
cat out.txthello
again
more
again
moreEach of the first three commands printed its own line. Then cat shows the file: again replaced hello, and more was added.
tee takes more than one file. It prints once, and each file gets a copy.
echo shared | tee one.txt two.txt three.txtshared- jobs.txt → grep: grep reads the jobs
- grep → tee: only the lines with fail
- tee → wc: tee passes them on
- tee → fails.txt: tee also saves a copy
tee can also sit in the middle of a pipe: it saves the text and passes it on. This command saves the failed jobs in fails.txt and prints how many there are. printf prints text from a template, and \n ends a line.
printf 'ok 1\nfail 2\nok 3\nfail 4\n' > jobs.txt
grep fail jobs.txt | tee fails.txt | wc -l
cat fails.txt2
fail 2
fail 4tee copies stdin only. To keep the errors of a command as well, join them to stdout first: ls missing 2>&1 | tee run.log prints the complaint on the screen and writes it into run.log.
Your turn
Run this block once. It only builds the data and clears the old files.
mkdir -p ~/krlab/linux-basics/streams && cd ~/krlab/linux-basics/streams
rm -f errors.txt review.txt out.txt err.txt
cat > events.txt <<'EOF'
INFO service started
INFO user alice logged in
ERROR disk almost full
WARN slow response
INFO user bob logged in
ERROR timeout on port 443
WARN certificate expires soon
ERROR login failed for root
INFO service stopped
EOFDo these tasks in order, with no steps given.
- With one command, save the
ERRORlines ofevents.txtin the fileerrors.txtand print how many there are. - Run
ls events.txt missing.txtso that the file name goes intoout.txtand the complaint goes intoerr.txt. Nothing may print on the screen. - With one command, add the line
reviewedto the end oferrors.txtand write the same line into a new filereview.txt. - Look for the word
CRITICALinevents.txtand printalarmif it is there, andcalmif it is not.
Check yourself
What is the difference between "> file" and ">> file"?
> empties the file first and then writes. >> keeps what the file holds and adds at the end. Use >> for a log that grows, and take care with >.
Why does "ls missing | wc -l" print an error and a 0?
The pipe carries stdout only. The error goes to stderr, which is still the screen, and wc receives nothing, so it counts 0 lines. Use 2>&1 | to send both.
What is the difference between "A && B" and "A; B"?
With ; the command B always runs. With && it runs only when A ended with status 0.
Why use "tee" when you could run the command twice?
The command may be slow, may change its output, or may read a stream that you can read only once. tee runs it one time and keeps the exact output.
Field notes
>destroys a file without a question. In bash,set -o noclobbermakes>refuse to replace a file that exists (bash: keep.txt: cannot overwrite existing file), and>|forces it.- The shell, not the program, opens the file for
>. Sosudo echo x > /etc/filefails: the shell that you run, without root, opens the file. The fix isecho x | sudo tee /etc/file, becauseteeruns as root. This was not run here, because it needssudo. - Do not send stderr to
/dev/nullas a habit. A script that hides its errors hides its own faults. - A pipeline has the exit status of its last command. A failure in the middle is lost unless a script sets
set -o pipefail. Part 2 shows it. - Keep a record of what you did.
tee -a case.logafter each important command gives you a timeline that you can hand over.