If we want to copy-paste what we just wrote in stdin to stdout, we can use a redirect > or append >>.
How does tee also writing from stdin to stdout different?
If we want to copy-paste what we just wrote in stdin to stdout, we can use a redirect > or append >>.
How does tee also writing from stdin to stdout different?
tee has one input and two outputs (hence its name, after the tee component used in plumbing). Redirection using > or >> has one input and one output.
Using tee, you redirect stdin both to stdout and (a second copy) to the file specified as argument to tee. Redirection with > or >> can't do that.
For example if you type:
ls -l | tee file-list
you get a directory listing on the terminal and it is simultaneously copied to the file file-list. However if you type
ls -l > file-list
the directory listing is stored only in the file file-list, there is no output on the terminal.
tee has another side-effect.
– Philip Couling
Jul 12 '22 at 13:08
tee is useful.
– raj
Jul 12 '22 at 13:10
The context of why you are asking this is important.
Example:
cat one_file > another_file
When you do this, cat does NOT open another_file. Your shell opens the other file and sets the stdout of cat to that file descriptor.
This can be problematic if you are trying to write to a file that requires root privileges. So this will most likely not work.
sudo echo 1 > /some/root/owned/file
Above the shell tries to open /some/root/owned/file before executing sudo and does not have permission.
Where as this does work:
echo 1 | sudo tee /some/root/owned/file
That's because tee has been run as root and its tee that opens the file in this context. Not the shell
tee itself does. Now, via Raj's answer I get the concept and via your answer I have made an important distinction.
– kature
Jul 12 '22 at 13:15
tee version is commonly seen in tutorials. But both are valid.
– Philip Couling
Jul 12 '22 at 15:33
The difference in redirecting output to a file with either >, >> or command | tee -a filename is that with tee you are able to set modes that can handle errors in different ways and that tee can write/append to files and the terminal. Sometimes people use tee because they want to see the output of the command in their terminal and also have it saved to a file, >/>> cannot do that.