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

Stop looking up the same command twice.

Ask about any command you run into and see what it actually does. Terminaster then brings it back just before you would forget it, until you can type it without searching.

Terminaster's tutor answering “What does chmod 754 mean?” by taking the command apart: chmod, then 7 for you, 5 for your group, 4 for everyone else, and the file name