Skip to content

Write to files: echo with > and >>

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.

Lesson 8 of 166 minSkip to the terminal ↓

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).

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

Your task

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

  • lists/shopping.txt exists (not done yet)
  • It holds eggs, flour and milk, one per line, in order (not done yet)

Lesson 8 of 16.

learner@sandbox: ~bash (practice)
Note: Practice shell for this lesson. Type a command and press Enter (help lists them all).