In some cases, it's necessary to print an output on stdout
and save an output in a file. In general, command output can either be printed or can be saved in a file. To solve it, the tee
command is used. This command reads from the standard input and writes to both standard output and files. The syntax of tee
will be as follows:
tee [OPTION] [FILE …]
The tee
command copies the output to each FILE
and also to stdout
. The OPTIONS
can be as follows:
Option |
Description |
---|---|
| |
|
Writing an output to stdout
and file: In general, to write an output to stdout
and file, we will call the same command twice, with and without redirection. For example, the following command shows how to print an output on stdout
and save it to a file:
$ ls /usr/bin/*.pl # Prints output on stdout /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl $ ls /usr/bin/*.pl> out.txt # Saves output in file out.txt
We can do both the tasks by running the ls
command once using the tee
command as follows:
$ ls /usr/bin/*.pl| tee out.txt # Output gets printed to stdout and saved in out.txt /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl $ cat out.txt #Checking content of out.txt /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl
We can also specify multiple filenames to tee
for an output to be written in each file. This copies the output to all files:
$ ls /usr/bin/*.pl| tee out1.txt out2.txt /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl
By running the above commands, the output will be also written to the out1.txt
and out2.txt
files:
$ cat out1.txt /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl $ cat out2.txt /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl
The tee
command also allows you to append the output to a file instead of overwriting a file. This can be done using the -a
option with tee
. Appending an output to a file is useful when we want to write an output of various commands or an error log of different command execution in a single file.
For example, if we want to keep the output of running the ls
and echo
commands in the out3.txt
file and also display results on stdout
, we can do as follows:
$ echo "List of perl file in /usr/bin/ directory" | tee out3.txt List of perl file in /usr/bin/ directory $ ls /usr/bin/*.pl| tee -a out3.txt /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl $ cat out3.txt # Content of file List of perl file in /usr/bin/ directory /usr/bin/rsyslog-recover-qi.pl /usr/bin/syncqt.pl
We can also use the tee
command to provide an output of a command as an input to multiple commands. This is done by sending the tee
output to pipe:
$ df -h | tee out4.txt | grep tmpfs | wc -l 7
Here, the output of the df -h
command is saved to the out4.txt
file, the stdout
output is redirected to the grep
command, and the output of the search result from grep
is further redirected to the wc
command. At the end, the result of wc
is printed on stdout
.
18.217.80.88