In this article, we cover how to echo into a file. The echo command mainly outputs its arguments in the standard output. If we wish to display “Hello World!” in the standard output then, we can use:
echo Hello World!
It would come up with:
Hello World!
Just like we could display the passed arguments to the standard output. Similarly, it is possible to append a file through the echo command.
echo into a file
We are mainly redirecting the output of a command to a file here. We have already covered that in a separate article. This one specifically deals with the echo command.
Use > greater than operator to redirect the output of the echo command to a file. Use the following syntax:
echo [arguments] > <file_name>
For instance, to write “Hello World!” to a file: test-file
echo Hello World! > test-file
Now, we can check the output of test-file through the cat command-line utility:
cat test-file
Word of Caution: This would replace everything stored in the file. If we wish to append the file then use >> two greater than operators.
echo Hello World1 >> test-file
This would add Hello World1 at the end of the file, without replacing the contents above.
Hello World! Hello World1
Not only the text, but we can also append the file with everything that can be passed as arguments for the echo command.
We reiterate that it is important to understand that a single > greater than operator would erase the entire content of a file. And, we should be extra careful while using that. If you just wish to enter text at the end of the file then it is better to use >> two greater than operators.
Though at this point in time, it may not seem much exciting to talk about. But, just imagine losing your entire work just because of a single error of using > in place of >>. In no way do we suggest using the >> operator at all times. In certain circumstances, > operator would come in handy.
In conclusion, we have covered how to echo into a file here.