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.dYour 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
appleErrors 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
2Bash 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 okBecause the data continues to stdout, you can place tee in the middle of a pipeline:
$ cat fruit.txt | tee copy.txt | wc -l
3Like >, tee overwrites the file. Add -a to append.
$ date | tee -a history.logtee with sudo
This often fails with "Permission denied":
$ sudo echo "nameserver 192.0.2.1" > /etc/example.confYour 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.confHere 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
- Run
ls /usr/bin | wc -l. - Run
ls /usr/bin | tee programs.txt | wc -l. - Check the saved file with
head programs.txt. - 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.