Linux tee Command Examples

Filed Under: UNIX/Linux
Linux Tee Command Examples

In this article, we shall go through the tee command in Linux. This is commonly used to read the input and write to both the Standard Output (stdout) and to one or more files.

The tee command is commonly used along with other commands through the pipe (|) operator.

Let us understand how this command works through a few examples.


Linux tee Command Syntax

The tee command is used with the following syntax:

tee [-OPTIONS] [FILES]
  • -OPTIONS represent the various possible options along with the tee command.
  • FILES represent all the files that tee writes the output data to, along with stdout.

tee Command Options

There are different options for the tee command that changes the behavior of the command. The below table summarizes this for us.

Tee Command Options
Tee Command Options

Usage of tee Command in Linux

1. Write to multiple files

The most simple usage of this command would be to write to both the stdout and to all the given files. But since we need to give input to stdin of tee, it is commonly used in a pipeline sequence.

The below example shows this:

echo 'HELLO WORLD' | tee out1.txt out2.txt

This echoes HELLO WORLD and redirects the stdout using the pipe operator and passes it into tee. We will get the string HELLO WORLD written to both the Console, as well as to out1.txt and out2.txt.

Output

Linux Tee Command Basic Example
Linux Tee Command Basic Example

2. Append to multiple files

By default, the tee command overwrites the files specified as arguments. To avoid that, we can use the -a (--append) option to append to those files instead.

echo 'HELLO WORLD PART 2' | tee -a out1.txt out2.txt

Output

Linux Tee Command Append
Linux Tee Command Append

3. Ignore Interrupts

We can use the -i option to ignore any interrupt signals (such as Ctrl+C) during the execution of tee.

command | tee -i out.txt

4. Hide the Console Output

We can hide the output to the Console by redirecting the stdout of tee to /dev/null.

ls -l | tee out3.txt > /dev/null

This sequence writes the output of ls -l to out3.txt, without printing to the Console.

Output

Linux Tee Command Hide Console Output
Linux Tee Command Hide Console Output

Conclusion

In this article, we learned about the usage of the tee command in Linux, which is very useful for writing to multiple files. It is commonly used in a pipeline sequence, where you want to look at the intermediate output by printing to stdout.

We learned about how we can use the tee command with various options. I hope this helped you understand more about the tee command, which can be a very nifty tool for a programmer!

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages