Shell – How to Insert Newline Character into a File Using Echo

command lineechonewlinesshell

I would like to create a file by using the echo command and the redirection operator, the file should be made of a few lines.

I tried to include a newline by "\n" inside the string:

echo "first line\nsecond line\nthirdline\n" > foo

but this way no file with three lines is created but a file with only one line and the verbatim content of the string.

How can I create using only this command a file with several lines ?

Best Answer

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.

Related Question