TEE Command in Linux

TEE command is useful when you want to redirect the standard output to a file. Tee command should be already installed on your Linux Machine.

How to use Tee Command

[root@server ~]# cat file-1.txt | tee file-2.txt
a
b
c

This will overwrite all the contents of the file-2.txt with file-1.txt.
if want to keep the contents of the file-2.txt intact so you need -a option to append. As shown below.

[root@server ~]# cat file-1.txt | tee -a file-2.txt
one
word

Redirecting out of a command to a file. Most of us have habit of using >> to redirect output of a command to a file. But that’s work all the time where there is a error in the script.

So, to redirect output of a command to a file you need to use below command.
Example, my script has error but when I use >> to redirect output it won’t work.

[root@server scripts]# ./servicestatus.sh >> error.log
./servicestatus.sh: line 1: !/bin/bash: No such file or directory
[root@server scripts]#

[root@server scripts]# ls -al error.log
-rw-r--r-- 1 root root 0 May 29 06:05 error.log
[root@server scripts]#

My error log file is blank, so here I will use TEE command which works perfect. It will re-direct stdout and stderr into a file.

[root@server scripts]# ./servicestatus.sh 2>&1 | tee error.log
./servicestatus.sh: line 1: !/bin/bash: No such file or directory
[root@server scripts]#

[root@server scripts]# ls -al error.log
-rw-r--r-- 1 root root 66 May 29 06:08 error.log
[root@server scripts]#

[root@server scripts]# cat error.log
./servicestatus.sh: line 1: !/bin/bash: No such file or directory
[root@server scripts]#

Leave a Reply

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