Skip to content

Write to files: echo with > and >>

Lesson 8 of 166 min

Save a command’s output to a file with >, add lines to the end with >>, and see why > can wipe a file. Practise redirection in a terminal in your browser.

Everything a command prints goes to the screen, unless you redirect it.

> sends output into a file

> followed by a file name sends the output into that file instead. The file is created if it doesn't exist:

echo "Pack the charger" > reminder.txt
cat reminder.txt

It works with any command: ls > files.txt saves a listing, head -n 3 notes.txt > top.txt saves three lines.

Careful: > empties the file before the command runs. Point it at a file that already has something in it, and that something is gone.

>> adds to the end

>> appends: the old contents stay and the new output goes after them. It's how you build a file a line at a time:

echo "first" > log.txt
echo "second" >> log.txt
cat log.txt

Errors are separate

Error messages travel on a separate channel, so > doesn't catch them; they still appear on screen. 2> redirects errors, and 2>/dev/null throws them away (/dev/null swallows anything written to it).

Tip:Quotes keep text together: echo "two spaces" keeps both spaces, which unquoted text wouldn't.

Your turn

Create lists/shopping.txt containing exactly three lines, in this order: eggs, flour, milk. Check it with cat.

Next →