Skip to content

Linux Foundations / Find your way around Linux ยท Step 34 of 63

Lesson: pipe and teeSwitch
โ† Linux Foundations

Shell and files

pipe and tee

Learn to chain commands with pipes and to save a copy of the stream with tee.

The most useful idea in the shell is that small programs can work together. A pipe passes the output of one command straight to the next, and tee saves a copy along the way.

The pipe

The | character connects the stdout of the command on the left to the stdin of the command on the right.

$ ls /etc | head -n 3
adduser.conf
alternatives
apparmor.d

Your list will differ. No temporary file is needed, and both commands run at the same time.

You can chain as many as you like:

$ cat fruit.txt | sort | head -n 1
apple

Errors are not piped

A pipe carries stdout only. Error messages still go to the terminal. To send both through, merge them first:

$ ls /etc/hostname /nope 2>&1 | wc -l
2

Bash 4 and later also accept |& as a shorthand for 2>&1 |.

Save a copy with tee

tee reads stdin and writes it to a file and to stdout.

$ echo "build ok" | tee status.txt
build ok
$ cat status.txt
build ok

Because the data continues to stdout, you can place tee in the middle of a pipeline:

$ cat fruit.txt | tee copy.txt | wc -l
3

Like >, tee overwrites the file. Add -a to append.

$ date | tee -a history.log

tee with sudo

This often fails with "Permission denied":

$ sudo echo "nameserver 192.0.2.1" > /etc/example.conf

Your own shell opens the file, and it is not running as root. sudo applies only to echo. Let tee do the writing:

$ echo "nameserver 192.0.2.1" | sudo tee /etc/example.conf

Here tee runs as root, so it can open the file. Be careful: it overwrites unless you use -a.

A last detail: a pipeline's exit status is normally that of the last command. Bash's set -o pipefail makes a failure earlier in the chain count too.

Practise in the streams and text lab.

Try it

  1. Run ls /usr/bin | wc -l.
  2. Run ls /usr/bin | tee programs.txt | wc -l.
  3. Check the saved file with head programs.txt.
  4. Append the date with date | tee -a programs.txt.

Check your understanding

pipe and tee

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.