This short guide shows you how to add a newline into a file by using the echo command on the Linux shell.
Add a Newline Character using echo command in Bash
In this example, I'll assume that we have a file example.txt with the following content:
Line 1 Line 2
Now we want to use the echo command, either on the command-line or in a bash script, to add this line:
Line 3
in a separate line at the end of the file. The command to do this is:
echo $'\nLine 3' >> example.txt
The Result is:
Line 1 Line 2 Line 3
So how does it work?
The "\n" stands for the newline character. The $ in front of the quotes instructs Bash to expand the ANSI sequences inside the string. The >> then appends the output of the echo command to the file. And what if we would want to write our example file consisting of 3 lines with a single echo command? The command would be:
echo $'Line1\nLine2\nLine3' > example.txt