How to fix echo printing literal \n (backslash newline)

Problem:

You want to echo into a file like this:

echo_example.sh
echo "\ntest\n" > test.txt

but after doing that, test.txt contains the literal

echo_literal_output.txt
\ntest\n

Solution

Use echo -e (-e means: interpret backslash escapes):

echo_fix.sh
echo -e "\ntest\n" > test.txt

After doing that, test.txt will contain test with a newline before and after.


Check out similar posts by category: Linux