How to add text to a file with command

echo

At the begining we need to know the difference about > adn >>.
Both syntax are represent that you are redirecting the output of the command on its left hand side to the end of the file on the right-hand side.
But the difference of these two syntan is that

  • > : Meaning you are writting to a file, if it already existing, it will overwrite it.
  • >> : By contrest this syntax will only append context to file.

When you have writting permission to target directory

$ echo "Hello world" > HelloWorld.txt
or
$ echo "Hello world again" >> HelloWorld.txt

When you doesn't have writting permission to target directory

$ echo 'Hello world' | sudo tee HelloWorld.txt

when you need append to existing file insead of overwritting it, you can use -a or --append option after tee command

$ echo 'Hello world again' | sudo tee -a HelloWorld.txt
or
$ echo 'Hello world again' | sudo tee --append HelloWorld.txt

If you reall don't want to use tee ...

$ sudo bash -c "echo \"Hello world\" > HelloWorld.txt"
or
$ sudo bash -c "echo 'Hello world again' >> HelloWorld.txt"

cat

Basicily it's same usage as echo command above


Referance

  1. What does echo with ">>" symbol do?

  2. Sudo Echo “To” > File: Permission Denied [SOLVED]

  3. How can I write and append using echo command to a file

  4. Writing Text to File Using Linux Cat Command