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.
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.txtcat reminder.txtIt 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.txtecho "second" >> log.txtcat log.txtErrors 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.
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)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
>- Writes the output to a file, replacing what was in it
>>- Adds the output to the end of a file
echo- Print a line of text More on echo →