Connect commands

INPUT · Slides

Show it and keep it (`tee`)

01 / 06

With > you cannot see the screen

Keep something in a file with > and nothing appears on the screen. You cannot tell whether it worked, so you end up doing a cat afterwards to check.

ls > list.txtcat list.txt      # a second go, just to check

It would be nicer to do both at once. That is what tee is for.

02 / 06

tee is a T-shaped branch

The name comes from the letter T. Picture a T-shaped joint in a water pipe: one in, two out.

ls | tee list.txt

It writes what it received to a file and puts it out the way out at the same time. So it appears on the screen and stays in the file.

Think of it as a replacement for >. The only difference is whether it shows on the screen.

~ $ ls | tee list.txtfruit.txtnames.txtrecord.txt~ $ cat list.txtfruit.txtnames.txtrecord.txt

03 / 06

It can sit in the middle of a pipe

Here is where tee really earns its keep: it can sit in the middle of a pipe.

sort fruit.txt | tee sorted.txt | uniq -c

The flow goes like this.

1. the result of sort reaches tee
2. tee writes it to sorted.txt
3. and passes it on to uniq -c at the same time

You get to keep what things looked like partway without stopping the flow. With > the flow ends there, so this is something only tee can do.

04 / 06

It shines when you are investigating a long pipe

When a pipe of five stages does not give what you expected, you cannot tell which part is wrong. That is when you slot a tee in.

A | tee 1.txt | B | tee 2.txt | C

Now A's output is in 1.txt and B's is in 2.txt. You can open them in order afterwards and see at which stage things went strange.

If you write programs, this will feel like the same thing as "put a print in the middle to check". tee is how you do that in a pipe.

05 / 06

tee -a, and writing to several

Just as > has >>, tee has a way to add: -a for append.

date | tee -a record.txt

And you can line up several places to write to.

ls | tee a.txt b.txt c.txt

The same thing goes into three files at once, which > cannot do (it takes one).

If you do not want it on the screen, add > /dev/null on the end. "A tee that only writes to files" is a real way to use it.

06 / 06

Now have a go

You have fruit.txt (six lines of fruit), names.txt (three names) and record.txt (one heading line).

What to keep an eye on this lesson is whether the flow carries on.

  • > — the flow ends there
  • tee — the flow carries on

Get that difference and you can use tee.