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.
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.
How about:
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: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 thenoclobber
variable in your.bashrc
:Now when you try to do
echo "hello" > file.txt
you will get a warning sayingcannot overwrite existing file
.To force writing to the file you must now use the special syntax:
You should also know that by default
echo
adds a trailing new-line character which can be suppressed by using the-n
flag:References
echo(1) - Linux man page
noclobber variable
I/O Redirection
Follow up to accepted answer.
You need something other than CTRL-D to designate the end if using this in a script. Try this instead:
This will append text to the stated file (not including "EOF").
It utilizes a here document (or heredoc).
However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.
This variation will work when you are typing directly on the command line:
Or you can use
tee
instead to avoid the command line sudo issue seen when using the heredoc with cat:Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.
Other possible way is:
The
-a
will append at the end of the file.If needing
sudo
, use: