Running a command again with > leaves only the latest output in the file. A log that grows from run to run is written another way.
Before running the command, the shell opens the file named after >. If the file exists, the shell wipes its contents; if not, it creates an empty one. Only then does the command start. That is why the old text is gone even when the command fails without printing a single line.
>> opens the file for appending: the output goes to the end, and the old lines stay. If the file does not exist, >> creates it, just like >. This is how logs are kept: each run adds a line.
The error stream works the same way: 2> overwrites the file, 2>> appends to it.
notes.txt held the line first. You ran ls /no-such-dir > notes.txt, and ls printed an error. What is in notes.txt now?
-
The shell wiped notes.txt before ls started, before the error happened.
cat notes.txtprints nothing. -
The message went to stream 2, the screen:
>redirected stream 1, and ls printed nothing to it. -
>wiped the file before the command started, sofirstis gone; the message went to stream 2, the screen. Appending is>>.
The shell opened notes.txt for > and wiped it before ls even started. ls printed nothing to stream 1 and sent the error to stream 2 — the screen. That is why cat notes.txt prints nothing.
Key points
-
>wipes the file before the command even starts;>>appends the output to the end. -
A file that grows from run to run is kept with
>>and2>>.