The Linux shell has several operators to redirect or pipe the output of commands into a file. In this guide, I will show you several ways to redirect the echo output into a file. We will replace the content of a file with the echo output, then we will append text to an existing file using echo and finally, we will echo text to a file on a remote system by SSH. All examples that are shown here work on any Linux distribution like Ubuntu, Debian, Linux Mint, Rocky Linux, etc.
Echo Into File
The “>” operator is used to replace the content of a file with the text that is returned by the echo command.
echo "some text here" > /path/to/file
$ echo "Greetings from Vitux.com" > /tmp/test.txt
The command will not show any result on the shell, the whole output is saved to the file. Now check the content of our file /tmp/test.txt. I’ll use the cat command:
Add more content to the file using Echo
In the second example, I will add content to our file /tmp/test.txt without replacing the content. the content will get appended to the end of the file. The operator used for appending content is “>>“.
echo "Some text to be appended" >> /path/to/file
echo "More text from Vitux here" >> /tmp/test.txt
The above command appends the text “More text from Vitux here” to the file /tmp/test.txt. The test.txt file contains already the text “Greetings from Vitux.com” from our first example. Now let#s see what’s in the file, I’ll use the cat command again to show the file content on the shell
Echo into file on Remote System
Sometimes you might want to write text into a file that is on another Linux system. As long as both systems are connected over a LAN or the Internet, then you can use SSH to do that. The ssh command has the -f command line switch to pass commands directly by ssh and then go to the background which allows you to enter a password (if required).
ssh [email protected] -f 'echo "Text added via SSH" >> /tmp/test.txt'
Where “user” is the username that you like to log in to the remote server or desktop. Replace the word “remotesystem” with the hostname or IP address of the remote computer.
I’ve run the command on a remote system to add some text to our test.txt file. The result is:
Now you have learned how to echo text into a file on the local system and also how to do this on a remote system via SSH.