73

Why is it that almost all instructions regarding appending text to system files like fstab and /etc/apt/sources.list.d/<name>.list involve using tee and echo to append said text?

Take the following examples, which are run as root:

## 1
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | tee -a file1
## 2
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' >> file2

Running diff -u file1 file2 returns nothing; running md5sum file1 file2 shows their checksums are identical, which brings me back to my original question:

Why is the | tee <FILENAME> so prevalent across Ubuntu docs, is it just good practice, otherwise wouldn't it be easier to just use example 2 instead of passing the output from echo to tee?

Alexej Magura
  • 1,396
  • 1
  • 10
  • 14

3 Answers3

110

There is a difference: tee duplicates the output: it sends it both to the file and to the display.

But there is more:

  • For example, if you want to write some string into two files at once, the command with tee you can use is:

     echo "some text" | tee file1 > file2  
    
  • Another thing tee can help you is to avoid one problem when using sudo. The normal output redirection operator is always executed with your user privileges, also when you write a sudo in front of the command which generates the STDOUT text. In other words, this will fail if you dont have the permission to write to that file:

     sudo echo "something" > bar  
    

    But with tee, everything will go well:

    echo "something" | sudo tee bar  
    

2 examples from this site. It has some more.

Rinzwind
  • 309,379
36

tee takes the standard input stream and writes it to both the standard output stream as well as a file stream. If it helps people remember, the command name comes from a T-splitter in plumbing. There is a nice Wikipedia article where I learned about the origin of the command name.

enter image description here enter image description here

user391339
  • 1,639
18

First of all, tee itself doesn't append text, nor does >.

It is tee -a and its complement, >> that APPENDS text.

I don't believe all shells support the >> function, so that is why tee is more commonly used. (Think of just plain old sh). Tee is a command, while >> is an operator.

If you use (my personal favorite) bash, > and >> are much nicer/easier.

Using tee also allows you to sudo JUST that command so you don't have to sudo the entire statement, as in sudo sh -c "echo foo > bar". tee also allows you to split the output. Of course, all of this can be seen in man tee. It's mainly just your personal preference.

For further reading, see here and here.

Kaz Wolfe
  • 34,680