Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 1 · Basics · Lesson 06 · 40 minutes

Join commands with pipes, redirects and tee

After this lesson you can
  • 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
Lab files of this lesson (6)

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.

The three streams of ls log.txt missing
Your terminalThe programA fileKeyboardScreenlserr.txt123Your terminalThe programA fileKeyboardScreenlserr.txt123
  1. Keyboard → ls: stdin (0): input; ls does not use it
  2. ls → Screen: stdout (1): log.txt, the result
  3. 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.

SymbolWhat 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>&1Send 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 missing
ls: cannot access 'missing': No such file or directory
log.txt

The 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.txt
second
second
third

The 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.txt
log.txt
cat err.txt
ls: cannot access 'missing': No such file or directory

Second, 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.txt
ls: cannot access 'missing': No such file or directory
log.txt
The command with two redirects
ls log.txt missingthe command and its names> both.txtstdout goes into both.txt2>&1stderr follows stdoutls log.txt missingthe command and its names> both.txtstdout goes into both.txt2>&1stderr follows stdout

Third, 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.txt
ls: cannot access 'missing': No such file or directory
cat only.txt
log.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 -l
2
ls: cannot access 'missing': No such file or directory
0
1

5. 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 entered
log.txt
status 0
ls: cannot access 'missing': No such file or directory
status 2
found
missing
bash: cd: missing: No such file or directory

The 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.txt
hello
again
more
again
more

Each 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.txt
shared
tee in the middle of a pipe
PipeFilesgrepteewcjobs.txtfails.txt1234PipeFilesgrepteewcjobs.txtfails.txt1234
  1. jobs.txt → grep: grep reads the jobs
  2. grep → tee: only the lines with fail
  3. tee → wc: tee passes them on
  4. 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.txt
2
fail 2
fail 4

tee 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
EOF

Do these tasks in order, with no steps given.

  1. With one command, save the ERROR lines of events.txt in the file errors.txt and print how many there are.
  2. Run ls events.txt missing.txt so that the file name goes into out.txt and the complaint goes into err.txt. Nothing may print on the screen.
  3. With one command, add the line reviewed to the end of errors.txt and write the same line into a new file review.txt.
  4. Look for the word CRITICAL in events.txt and print alarm if it is there, and calm if 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 noclobber makes > 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 >. So sudo echo x > /etc/file fails: the shell that you run, without root, opens the file. The fix is echo x | sudo tee /etc/file, because tee runs as root. This was not run here, because it needs sudo.
  • Do not send stderr to /dev/null as 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.log after each important command gives you a timeline that you can hand over.