1. Overview

In this tutorial, we will learn how to append lines to the end of a file in Linux.

There are two standard ways of appending lines to the end of a file: the “>>” redirection operator and the tee command. Both are used interchangeably, but tee‘s syntax is more verbose and allows for extended operations.

2. Appending a Single Line

We can append a line of text to a file using the output redirection operator “>>”:

$ echo "I am baeldung" >> destination.txt

The same can be accomplished using tee:

$ echo "I am baeldung with tee command" | tee -a destination.txt

3. Appending Multiple Lines

In order to append multiple lines, we can use the echo command and just hit the return key to type over multiple lines. Once we are done we just use the redirection append operator “>>”:

$ echo "I just wrote a great tutorial for baeldung
> and I believe it will increase your understanding 
> of the Linux operating system" >> destination.txt

Another way to accomplish this is to use the cat command and include a string that represents the End-of-File (EOF):

$ cat << EOF >> destination.txt 
> I just added some more good stuff
> tell me what you think 
> EOF

The same can be accomplished using the tee command:

$ cat << EOF | tee -a destination.txt
> I just added some more good stuff
> tell me what you think
> EOF

4. Appending Both stdout and stderr

By default, the redirection operator only appends the stdout stream. For us to be able to append the stderr as well we need to specify it.

In order to append to the same file, we can just place the “&” symbol before the “>>”:

$ cat not_there.txt &>> output_and_error.txt

If we want to split this steams into different files, we can accomplish it by specifying which streams go where:

$ cat not_there.txt >> destination.txt 2>> output_and_error.txt

5. Appending with sudo

The sudo command comes in handy to run commands at the system root level. In order to combine it the redirection mechanisms we’ve been exploring, we need to call bash as a command and pass the command we want to run as an argument:

$ sudo bash -c 'echo "I just added some text using Sudo" >> destination.txt' 

As for the tee command, we just call it with sudo:

$ echo "I just did this using Sudo again" | sudo tee -a destination.txt

6. Conclusion

In this tutorial, we saw how to append single and multiple lines to the end of a file using both tee command and the “>>” redirection operator.

Comments are closed on this article!