This tutorial explains how to append text to a file in Bash. There are different ways to append text to a file.
Your user must have write permission to a file in which you want to append text. Otherwise, you will receive a permission denied error.
Append Text using Redirection Operator (>>)
Using Redirection you can take the output from a command and put it as input to another command or file. The
>> redirection operator appends the output to a given file.
There are many commands that are used to print text to the standard output, such as
printf are being most used. Following is the example to add text to file using
echo "this is a new line" >> filename.txt
In above command you should specify the file name after the redirection operator. You should use the
-e option with the echo command to interpret the backslash-escaped characters such as newline
echo -e "this is a first line \nthis is second line" >> filename.txt
If you want to specify the formatting output, you should use
printf "Hello, I'm %s.\n" $USER >> filename.txt
Append Text using the tee Command
In Linux, the
tee is a command-line utility, which reads from the standard input and writes to both standard output and files at the same time.
By default, the tee command overwrites the specified file. To append the output to the file use tee with the
echo "this is a new line" | tee -a file.txt
If you don’t want tee to write to the standard output, redirect it to
echo "this is a new line" | tee -a file.txt >/dev/null
The main benefit of
tee command over the redirection operator is,
tee allows to you to append text to multiple files at once, and to write to files owned by other users in conjunction with sudo.
To append text to a file that you don’t have write permissions to, you should use
tee as shown below:
echo "this is a new line" | sudo tee -a file.txt
To append text to more than one file, specify the files as arguments to the
echo "this is a new line" | tee -a file1.txt file2.txt file3.txt
In Linux, to append text to a file in bash, use the
>> redirection operator or the tee command.
If you have any questions or feedback, feel free to leave a comment.