How do I append text to a file?

Dchris picture Dchris · Jul 17, 2013 · Viewed 262.6k times · Source

What is the easiest way to append text to a file in Linux?

I had a look at this question, but the accepted answer uses an additional program (sed) I'm sure there should be an easier way with echo or similar.

Answer

Cyclonecode picture Cyclonecode · Jul 17, 2013

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References