How to write multiple lines to a file using echo?

QuestionsQuestions8 SkillsProDec, 18 2025
0300

That's a great follow-up question! While echo is simple, there are a few clever ways to use it to write multiple lines to a file.

Here are the most common methods:

1. Using the -e flag with \n

The -e flag enables the interpretation of backslash escapes. \n is the special code for a "new line."

echo -e "Line one\nLine two\nLine three" > myfile.txt
  • >: This symbol creates a new file (or overwrites it if it already exists).

2. Using Quotes and Literal Enters

You can actually press Enter while the quotes are still open. The terminal will wait for you to close the quote before running the command.

echo "Line one
Line two
Line three" > myfile.txt

3. Appending multiple times

If you want to add lines one by one without deleting what is already there, use the double arrow >> (which means append).

echo "First line" > myfile.txt
echo "Second line" >> myfile.txt
echo "Third line" >> myfile.txt
  • >: Overwrites the file.
  • >>: Adds to the end of the file.

How to check your file:

After running any of the commands above, you can see the results by typing:

cat myfile.txt

Give it a try in your LabEx terminal! It's a very useful skill for creating configuration files later on.

0 Comments

no data
Be the first to share your comment!