How to use tee
to read from stdin and output to stdout and files? This article, I will introduce you to the tee command.
If you forget what stdin and stdout are, read the article overview of I/O redirection.
About tee command
Table of Contents
Linux provides a tee
command, but according to the man page, it will read from standard input and write to standard output and files.
It is often used in the pipeline, what does this mean? In the past, most of you only saw pipeline examples of exporting the final data to the screen or file.
But what about in the middle stage? If you want to save data at the middle stage of a pipeline to a file, how will you do it?
Tee commands will help you do that. This command syntax:
$ tee [option]... [file]...
In the pipeline:
$ command-1 | tee [option] [file] | command-n
Example of using tee command
We will make an example quite familiar with the pipeline. List content in the /bin
directory.
In the middle stage, we use the tee
command to save the data to the file. Next, the tee
command will output the data to the grep
command in the pipeline for further processing.
Recommended Reading: Understand long format of ls command in Linux
$ ls /bin | tee ls-bin.txt | grep zip
bunzip2
bzip2
bzip2recover
gunzip
gzip
You can see in the image above, previously the folder is empty. When executing the pipeline, we see two things that happen simultaneously.
- Data from ls command has been written to
ls-bin.txt
file. - The
tee
command continues to output data for thegrep
command in the pipeline.
Conclusion
In the process of running long pipelines, you need to log what is happening at the middle stage. Tee command will help you solve that problem.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).