How to Append Output to a File in Linux Shell
In the Linux operating system, appending output to an existing file
allows you to add new data to the end of a file without overwriting its
current contents. This guide covers the most efficient methods to
accomplish this using native shell redirection operators like
>>, handling standard error with
2>>, and utilizing the tee command for
simultaneous terminal viewing and file appending.
1. Using the
>> Redirection Operator
The primary and most common method to append standard output
(stdout) to an existing file is the double greater-than
operator (>>). If the destination file already
exists, the output is added to the end. If the file does not exist, the
shell automatically creates it.
To append a simple text string:
echo "This is a new line" >> filename.txtTo append the output of a command:
date >> system_log.txt
ls -la >> directory_contents.txtNote: Avoid using a single > operator, as it will
overwrite (truncate) the existing contents of the file instead of
appending to it.
2. Appending Error Messages
(stderr)
By default, the >> operator only appends standard
output (stream 1). If a command generates an error message (stream 2),
it is displayed on the screen rather than written to the file.
To append only standard error to a file, use
2>>:
command_with_errors 2>> error_log.txtTo append both standard output and standard error into the same file,
use &>>:
command_name &>> combined_output.txtAlternatively, in older shells (such as legacy Bourne shells), you can redirect standard error to standard output:
command_name >> combined_output.txt 2>&13. Using the
tee Command with the -a Flag
The tee utility reads from standard input and writes to
both standard output (the terminal) and files simultaneously. By
default, tee overwrites files, but adding the
-a (or --append) flag forces it to append.
Basic syntax:
echo "New entry" | tee -a filename.txtAppending with Root Privileges
A common problem occurs when attempting to append to a file owned by
the root user using standard redirection:
# This will fail with a "Permission denied" error:
sudo echo "127.0.0.1 custom.domain" >> /etc/hostsThis fails because the redirection is handled by your user shell, not
sudo. To resolve this, use tee -a with
sudo:
echo "127.0.0.1 custom.domain" | sudo tee -a /etc/hosts