Shell, explained

> vs >> in the terminal: overwrite or append?

echo "buy milk" >> todo.txt

> writes a command's output into a file and replaces everything that was in it. >> adds the output to the end of the file and keeps what was there. Both create the file if it does not exist yet.

> replaces the file

The two old lines are gone; todo.txt now holds only what echo printed.

$

Tap a part of the command to find it below

$ echo "buy milk"

output → todo.txt

>todo.txtREPLACED
−walk dog
−water plants
buy milk
Tap any part of the command to see what it does

>> adds to the end

The old lines stay and the new one is appended after them.

$

Tap a part of the command to find it below

$ echo "buy milk"

output → todo.txt

>>todo.txtAPPENDED
walk dog
water plants
+buy milk
Tap any part of the command to see what it does

Part by part

echo "buy milk"
Prints the text buy milk.
>
Sends that output into a file, emptying the file first.
>>
Sends that output into a file, after whatever is already in it.
todo.txt
The file. It is created if it does not exist.

Common mistakes

Overwriting a file you are reading

sort todo.txt > todo.txt leaves you with an empty file: > empties it before sort reads it.

Using > when you meant >>

One missing > wipes a log or a list. In bash, set -o noclobber makes > refuse to overwrite an existing file (use >| when you really mean it).

Try it

$ date >> log.txt

Run it twice, then cat log.txt: two lines.

$ date > log.txt

Back to one line.

$ : > log.txt

Empty a file without deleting it.

Questions

Do > and >> create the file?

Yes. If the file does not exist, both create it. They fail only if you cannot write in that folder.

How do I append with sudo?

sudo echo x >> /etc/file fails, because the redirection is done by your own shell, not by sudo. Use echo x | sudo tee -a /etc/file instead.

How do I save errors too?

Add 2>&1 after the file: cmd >> log.txt 2>&1. In bash 4+ and zsh, cmd &>> log.txt does the same.

Terminaster

Ask about any command and get a picture like this one.

The Terminaster tutor draws these visuals for your own questions, then turns what you learned into spaced-repetition cards so it sticks.