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
output → todo.txt
>> 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
output → todo.txt
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.txtRun it twice, then cat log.txt: two lines.
$ date > log.txtBack to one line.
$ : > log.txtEmpty 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.
The ideas behind it
Redirection
Redirection is shell syntax that opens, closes, or duplicates file descriptors for a command before that command begins executing.
Standard input, output, and error
A command-line process normally starts with three conventional open streams: standard input for incoming data, standard output for primary results, and standard error for diagnostics.