Tee
tee is a small program in GNU coreutils which can redirect input to a file while piping it on to another program as standard output. This can be really useful if you want to do two things with one program's output.
A Basic Example[edit]
The simple command cat /proc/cpuinfo
will show all kinds of incriminating information about your CPU if you are using a Linux kernel. grep
can be used instead of cat
to get specific information like the frequency. grep MHz /proc/cpuinfo
will produce a list of current CPU frequencies like:
cpu MHz : 2171.574 cpu MHz : 2214.082 cpu MHz : 2660.394 cpu MHz : 2215.162
This information can be piped on to another program to get useful data. It is, as an example, possible to send it to awk
and use awk to get an average:
grep MHz /proc/cpuinfo | awk '{sum+=$4} {max = 0} {if ($4>max) max=$4} END {print "max: " max "\naverage: " sum/NR}'
That command will produce the output
max: 3325.255 average: 2608.43
Notice how the list of CPU frequencies from grep MHz /proc/cpuinfo
is gone - awk
ate it and turned it into the max and average values. What can you do if you want both the frequencies fed to awk
and it's output? That is exactly what tee
is for. In this case you can have your cake and eat it too.
In this case we want the output to be sent to a terminal. /dev/stderr
can be used for this purpose, echo error > /dev/stderr
will output "error" in the terminal. Thus, we can use tee
with /dev/stderr
as an argument to get the output from grep
printed in the terminal and have it sent to awk. The full one-liner would be:
grep MHz /proc/cpuinfo | tee /dev/stderr | awk '{sum+=$4} {max = 0} {if ($4>max) max=$4} END {print "max: " max "\naverage: " sum/NR}'
cpu MHz : 3523.833 cpu MHz : 3583.771 cpu MHz : 3650.230 cpu MHz : 3688.620 max: 3688.620 average: 3495.35
tee -a to append[edit]
tee
will by default overwrite any output file. This may not be what you want. -a
is a very useful option which tells tee
to append to files instead of overwriting them. It makes no difference if you write to /dev/stderr
and things like that but it can be hugely beneficial when you are working with regular files. Very simply:
echo hello | tee -a $HOME/hello.txt
will append the text to your hello.txt file while no -a
option like
echo hello | tee $HOME/hello.txt
will zero hello.txt and then write hello to it. The file will only contain "hello" afterwards.
links[edit]
The tee
manual page doesn't really have any additional information.
Enable comment auto-refresher