Bash Examples: Append to File
Table of Contents
>> operator allows us to append the standard output (stdout) of a command to the end of a file. The syntax is:
We can also leave out the spaces. All three lines below do the same thing:
$ $ $
It is also possible to append a command's standard error to a file using the same operator.
file does not already exist, it will be created.
To append "Hello, world!" to the end of the file
myfile.log, we can write:
echo command automatically adds a newline (line break) at the end of the text, this will add a newline to the end of the file as well.
If we want to append just the text without a newline at the end, we can use the
An alternative to using
echo is to use the
printf command, which allows you to specify an output format using special character sequences like
%s for "insert text string here" and
\n for newline (line break).
The first argument of
printf is the string that specifies the output format. To indicate that we want to display a text string (
%s) followed by a newline (
\n), we can use the format string
%s\n. Then, we can supply the content of the text string as the next argument to
printf. Putting it together, to append
Hello, world! followed by a newline, we can run the following command:
If we don't want the newline at the end, we can simply leave it out of the format string:
To append the contents of
file1.log to the end of
cat command prints the contents of
file1.log to standard output, and the
>> operator appends that output to the end of
cat does not automatically add a newline at the end of
file2.log. To add a newline, we can combine it with
This tells Bash to first store the output of the command
cat file1.log to a string and then pass that string into the
printf "%s\n" command we saw earlier.
The above examples have all shown how to append standard output from a command (
cat) to a file. But what if you want to append standard error (stderr)? For that, we can specify standard error by its POSIX file descriptor number
2, as shown below.
To append both standard output (which is always assigned file descriptor
1 in POSIX) and standard error (file descriptor
2) from a command to a file, we can write:
This first tells Bash to append standard output from
>> file), and then tells it to redirect standard error to whereever standard output is going (i.e., append to
Although standard output is implied when we write
>>file, we can also write
This example does the exact same thing as the previous example.
To append only standard error from a command to a file, we can write:
Standard output will be left alone, so if we run this command from a terminal command line, standard output will show up on screen while standard error will be appended to
To append standard output to
out.log and standard error to
err.log, we can write:
We can also leave out
1 since it is implied:
- 3.6 Redirections (Bash Reference Manual)