Introduction
There are several ways to append text to a file in Bash. Some of them are explained in this tutorial.
You must have written permissions to a file in order to append text to it. Otherwise, you will see a permission denied error.
Append to a File using the Redirection Operator (>>
)
You can use redirection to retrieve a command's output and use it as input for another command or file. The output is appended to a specified file by the >>
redirection operator.
There are a number of commands available that allow you to print text to the standard output and direct it to a file; the two most popular ones are echo
and printf
.
To append text to a file, specify the file name following the redirection operator:
echo "this is a new line" >> file.txt
The echo
command interprets backslash-escaped characters like newline \n
when used with the -e
option:
echo -e "this is a new line \nthis is another new line" >> file.txt
Use the printf
command, which enables you to specify the formatting of the output, to generate more complex output:
printf "Hello, I'm %s.\n" $USER >> file.txt
Using the Here document (Heredoc) is another way to append text to a file. It is a sort of redirection that permits many lines of input to be passed to a command.
For instance, you can append the content to a file by passing the content to the cat command:
cat << EOF >> file.txt
The current working directory is: $PWD
You are logged in as: $(whoami)
EOF
The output of any command can be appended to a file. Here's an example using thedate
command:
date +"Year: %Y, Month: %m, Day: %d" >> file.txt
Be careful not to use the >
operator to overwrite a crucial existing file when appending to a file using a redirection.
Append using the tee
Command
A Linux command-line tool called tee
reads from standard input and simultaneously writes to standard output and one or more files.
The tee
command overwrites the specified file by default. Use the tee command with the -a
(—append
) option to append the output to the file:
echo "this is a new line" | tee -a file.txt
Redirect tee
to /dev/null
if you do not want it to write to standard output:
echo "this is a new line" | tee -a file.txt >/dev/null
The tee
command has an advantage over the >>
operator in that it allows you to append text to many files at once and write to files held by other users when used in combination with sudo
.
If you want to append text to a file that you do not have write permissions to, prepend sudo
before tee
, as in the example below:
echo "this is a new line" | sudo tee -a file.txt
tee
receives the echo
command's output, lifts the sudo permissions, and writes to the file.
Use the tee
command with the files as arguments to append text to several files:
echo "this is a new line" | tee -a file1.txt file2.txt file3.txt
Conclusion
Use the tee
command or the >>
redirection operator on Linux to append text to a file.
If you have any queries, feel free to post a comment below, and we'll be happy to answer them.