How to put a newline special character into a file using the echo command and redirection operator?

You asked for using some syntax with the echo command:

echo $'first line\nsecond line\nthirdline' > foo

(But consider also the other answer you got.)

The $'...' construct expands embedded ANSI escape sequences.


What echo does with character escapes is implementation defined. In many implementations of echo (including most modern ones), the string passed is not examined for escapes at all by default.

With the echo provided by GNU bash (as a builtin), and some other echo variants, you can do something like the following:

echo -en 'first line\nsecond line\nthird line\n' > file

However, it really sounds like you want printf, which is more legible to my eye, and more portable too (it has this feature defined by POSIX):

printf '%s\n' 'first line' 'second line' 'third line' > file

You also might consider using a here document:

cat > file << 'EOF'
first line
second line
third line
EOF

Here are some other ways to create a multi-line file using the echo command:

echo "first line"  >  foo
echo "second line" >> foo
echo "third line"  >> foo

where the second and third commands use the >> redirection operator, which causes the output of the command to be appended (added) to the file (which should already exist, by this point).

Or

(echo "first line"; echo "second line"; echo "third line") > foo

where the parentheses group the echo commands into one sub-process, which looks and acts like any single program that outputs multiple lines (like ls, for example).

A subtle variation on the above is

{ echo "first line"; echo "second line"; echo "third line";} > foo

This is slightly more efficient than the second answer in that it doesn't create a sub-process.  However, the syntax is slightly trickier: note that you must have a space after the { and a semicolon before the }.

See What are the shell's control and redirection operators? for more information.