The tee
command is used to read the standard input and write and writes to both standard output and one or more files at the same time. Generally, tee
is used with combination of other commands through piping. In this tutorial, we’ll cover the basics of using the tee command.
tee Command Syntax
Below is the basic syntax of tee
command:
tee [OPTIONS] [FILE]
- Here, options are:
-a
(--append
) – It will append to the given file instead of overwrite.-i
(--ignore-interrupts
) – Ignore interrupt signals.- Use tee
--help
to view all available options.
- FILE – One or more files. Each of which the output data is written to.
How to Use the tee Command
Usually, the tee
command is used to display the standard output (stdout
) of a program and write it in a file.
For example, we will get the disk space details using df command and store the output to the output.txt
file by piping with tee command:
df -h | tee output.txt
Filesystem Size Used Avail Use% Mounted on
udev 984M 0 984M 0% /dev
tmpfs 200M 624K 199M 1% /run
/dev/vda1 25G 3.8G 21G 16% /
tmpfs 997M 0 997M 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 997M 0 997M 0% /sys/fs/cgroup
/dev/vda15 105M 3.6M 101M 4% /boot/efi
tmpfs 200M 0 200M 0% /run/user/1000
You can view the content of the output.txt
file using the cat command.
Write to Multiple File
You can also use tee
command to write to multiple files. Pass the list of files separated by space as arguments:
command | tee file1.txt file2.txt file3.txt
Append to File
Use the -a
(--append
) option to append the output to the file. The tee
command will overwrite the specified file.
command | tee -a file.txt
Ignore Interrupt
You can use -i
(–ignore-interrupts
) option to ignore interrupts. It’s useful when stopping the command during execution with Ctrl+C
and want to exit gracefully.
command | tee -i file.txt
Hide the Output
To hide the standard output, redirect it to /dev/null
:
command | tee file.txt >/dev/null
Using tee in Conjunction with sudo
When you try to write to a file owned by a root or sudo user, it will throw permission denied error. You should perform the redirection using sudo user.
sudo echo "newline" > /etc/nginx/file.conf
It will show something like this:
bash: /etc/nginx/file.conf: Permission denied
Simply prepend sudo before the tee command as shown below:
echo "newline" | sudo tee -a /etc/file.conf
The echo
command will pass the output to the tee
command and elevate to sudo permissions and write to the file.
Using tee
in conjunction with sudo
allows you to write to files owned by other users.
Conclusion
The tee
command reads from standard input and writes it to standard output and one ore more files.
If you have any questions or feedback, feel free to leave a comment.