How to Append to File in Bash [5 Methods]

Appending to a file is a process of adding new lines or content to the existing files. In this process, without changing the previous content, it adds a new line to the existing file. Append is essential for maintaining current data while concatenating new stuff. You can easily append to a file using the redirection (>>) operator with Linux commands. Let’s look for a few techniques to append in a file in bash.

Basic Syntax to Append to File in Bash

The basic syntax to append to a file involves the redirection operator (>>) along with the command. Redirection refers to the process of handling and altering the source of standard input and the destination of the standard output stream.

  1. To append lines to a file with the existing content one can use the following redirection command:
    command >> filename
  2. To append lines to a file and display the added line in the command line use the tee command:
    command | tee [option] filename
  3. To append a line at a specific position of a file use the sed command:
    sed [option] 'command' filename

Replace the command with your preferred one in the above commands. In thesedcommand, the 'command'refers to the operation that thesedcommand performs on the input.

5 Methods to Append to File in Bash

To append lines to a file, you can use the redirection operator with theecho, cat, andprintf commands. Using piping with theteecommand, one can append lines to a file. Thesedcommand allows you to append lines to a specific position in a file.

In this part, I will give an overview of the Five methods to check how to append a line to a file.

1. Append to File Using Redirection “>>” with “echo” Command

The echo command is a command line utility that is used to display the contents of a file in the terminal.

To append a new line to the file, you can use the echo command with the redirection operator (>>). The file name should be specified after the redirection operator. For example, run the following script:

#! /bin/bash
 echo "It is a new line." >> combo.txt

It will add the line at the end of the combo.txt file. Let’s see the content of combo.txt using the following command:

cat combo.txt
EXPLANATION

The>>operator redirects and appends the output of theechocommand to the file combo.txt.

Append single line to file with echo

From the output, you can see the new line appended at the end of the content.

To append multiple lines, use the following code:

#! /bin/bash
echo -e "Staurday\nSunday\nMonday\nTuesday\nWednesday\nThursday\nFriday" >> weekdays.txt

EXPLANATION
The-eoption interprets the backslash escape in the string. The\nis the newline character and indicates that it starts a new line. The output from theechocommand is redirected>>to the weekdays.txt file.
Append multiple lines to file with echo commandAfter executing the script, display the contents using thecatcommand following the file name. In the file, multiple lines have been added below the existing lines of the file.

2. Append to File Using Redirection “>>” with “printf” Command

The printf is a command line utility that is widely used to format and print text. This command provides more formatted and flexible output than echo.

To append lines to a file use the printf command with the redirection operator (>>). Here is how:

#! /bin/bash
printf "My name is %s.\nMy current working directory is %s.\n" $(whoami) $PWD >> printfile.txt

EXPLANATION
The%sindicates the format specifier for the string and is replaced by the command substitution $(whoami) and whoami replaces it with the name of the current user name.$PWDindicates the current directory. The output is redirected intoprintfile.txt.
Append lines to the file From the output, you can see new lines are added at the end of the file after executing the script.

3. Append to File Using Redirection “>>” with Here Document

Here document is a process of entering a string into a script and printing multiple lines of text. The basic syntax of here doc is:
command << Delimiter
Line1
Line2
Delimiter
Replace the command with the actual command you want to execute. Delimiter is the beginning and the end of the here document which is case-sensitive.
To append multiline to a file, you can use here document with the cat command and redirection operator. Here is how:

#! /bin/bash
cat <<EOF>> mealtime.txt
Breakfast will be at 9:30 AM.
Lunch will be at 2:30 PM.
Dinner will be at 9:30 PM.
EOF

EXPLANATION
The <<EOF has passed as input to the cat command. The <<EOF is the beginning of the text and with the delimiter EOF at the last, it indicates the end of the text. The value has been appended using >> in the file mealtime.txt.
To see the new line that has been appended to the file use the following command:
cat mealtime.txt
Append line to file with here documentThe new content has been added at the end of the existing content.

4. Append to file Using “Tee” Command

The tee command reads content from the standard input and writes it into the standard output and in the terminal. You can use the standard output if you want to append output to files.
To append a line to a file, you can use the tee command with the echo command and piping. Copy the following code:

#! /bin/bash
echo -e "Some other colors name has been added.\nmagenta\ngreen\nyellow\nred\sky-blue\npurple\nindigo" | tee -a colors.txt

EXPLANATION
The pipe (|) takes the output of theechocommand and uses it as input for theteecommand. The tee command displays the output and saves it. The-aoption is used to append text at the end.
Without using the-aoption, the tee command overwrites the file. To append the same line to multiple files you can use the following command:

echo -e “Line1.\nLine2.\n” | tee file1 file2 file3

Replace the Line and file name according to your preference.

Append line with tee command in bash

As you knowteecommand displays the standard output and saves it in a file. For that reason, after executing the script it shows the output of echo -e "Some other colors name has been added.\nmagenta\ngreen\nyellow\nred\sky-blue\npurple\nindigo" command.

Display output usinh cat commandFrom the output of the file, you can see the new lines are appended at the end of the file.

5. Append a Line to a Specific Position Using “sed” Command

The sed command refers to a process of modifying lines from the specified file argument and writing them to standard output. There are numerous features in the sed command to select a line to be modified and make changes.

To append a line at a specific line, use the sed command. Here is the code:

#! /bin/bash
sed -i '2i This is the new line' readable.txt
EXPLANATION

The2isays thesedcommand to append the following line at the position of line 2 and append it into the new file.

Append line at a specific position

The-ioption used in the command modifies the original file. If you want to see only the output without any modification of the original file then don’t use the-ioption.

Append Stderror to a file Using Redirection

The standard error refers to the output device to write the error message of a program which is separated from the normal output messages. It is denoted as stderr and by default shown on the screen. The standard error redirection operator is2>. Here 2 is the file descriptor. Using this operator one can redirect the error to a file.

To append std error to a file you can use the file descriptor of error which is 2 with redirection append operator>>. Here is how:

#! /bin/bash
ls /multiple 2>> error.txt
EXPLANATION

Thels /multipleindicates the list of contents of the directory named multiple under the root directory. The output from thels /multiplewill be redirected to theerror.txtfile.

If the output of the command shows no error then it will not append anything to the file.

Append error to a file

In the image first, you can see the error.txt before appending the error. Then after the execution of the script, the error is redirected to theerror.txtfile. You can see the standard error has been saved and shown using thecatcommand.

Append Both Stdout and Stderr

Standard output is the stream to which a command or a program writes output information. By default, it is also shown on the screen. The file descriptor of the stdout is1which is not mentioned with>because the>operator redirects the output by default.

To append both stdout and stderr to the same file you can use the2>&1syntax. Below the code has been shown:

#! /bin/bash
(whoami && date && ls /notexist) >> stdouterr.txt 2>&1
EXPLANATION

The&&ensures the execution of commands when the preceding command is executed. Here the whoami command prints the user name, the date command prints the current date and time and ls lists the contents in the directory named notexist. The>>redirects the output into the stdouterr.txt file. 2>&1indicates that the error and output will be stored in the same file.

Append standard output and error to a same file

From the output, you can see the output of the first two commands which are the user name and the date has been appended, and then the error of thels /notexistcommand has been appended.

In the newer version of bash, you can use&>and&>>instead of2>&1. This is how it looks in the code:

(whoami && date && ls /notexist) &> stdouterr.txt

The&>will overwrite the file.

(whoami && date && ls /notexist) &>> stdouterr.txt

The&>>will append the stdout and error in the same file.

Conclusion

Appending to a file in bash is a common operation that allows you to add a new line in an already existing file. The simplest method to add a new line to a file is through redirection, which has been demonstrated in this article along with other methods. Hope you will be able to choose a suitable method to append new lines to your files.

People Also Ask

How do I append two files?

You can append the contents of one file to another file using the following command:

cat file1.txt >> file2.txt

Here the content of file 1 will be appended with the content of file2. If file2 does not exist then a new file will be created.

Why should a new line character be added at the end of the file?

It is important to add a newline character. Because the new line character (\n) represents the end of a file and it starts a new line. For example, you want to add a few new lines like the following:

echo "line1.line2.line3."

Then the output will be line1.line2.line3. Without\nit won’t create a new line. It should be in mind while using echo, add the-eoption otherwise it won’t print a line into the new one.

Can I append a line at the beginning of a file?

Yes, the easy method to append a line at the beginning of a file is using of sed command; Here the command is:

sed -i '1i The new line.' filename

Here1imeans to add a new line at the position of the first line in the file named filename.

How do I concatenate multiple files into one?

If you can preserve the file contents of a file then you can merge multiple files into a new file by following the command:

cat file1 file2 file3 > combinedfile.txt

Here you can preserve the original content of file1, file2, and file3 and save it to file combinedfile.txt.

Can I save the standard output and standard error in the same file?

Yes, you can save the stdout and stderr to the same file using the following command:

ls document > output.txt 2>&1

The output of the command will be saved into the output.txt file. If you have a newer version of bash then you can use the following command:

ls document &>output.txt

Why does one use %s\n before the variable in appending line to a file?

With echo or printf commands, one uses%sto treat the input as a string and\nto add a new line character after each line.

Can I write to a file using a tee command?

Yes, you can write into a file using the tee command. To write in a file you can copy the following command:

echo -e "Some other colors name has been added.\n" | tee colors.txt

Replace the colors.txt file with your preferred file in which you want to save the content.

Related Articles


<< Go Back to Bash File & Directory Operations | Bash Files and Directories | Bash Scripting Tutorial

5/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Afia Zahin Oishi

Assalamualaikum, I am Afia Zahin, completed my graduation in Biomedical Engineering from Bangladesh University of Engineering and Technology, currently working as a Linux Content Developer Executive at SOFTEKO. A high achieving professional with a strong work ethic and able to work in a team in order to consistently achieve my goal and build my skillset. Able to handle difficult problems with patience and swift decision-making. Read Full Bio

Leave a Comment