Linux Labs

First steps / Stage 11 of 15

Where a command's output goes

Not running Starting usually ~20 s
Leave the lesson

Step 3 of 6 · theory · 4 min

Appending to the end

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.

bash
date >> checks.log    # appends a dated line to checks.log
date >> checks.log    # the second line lands under the first

The error stream works the same way: 2> overwrites the file, 2>> appends to it.

Check yourself 1 question

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.txt prints 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, so first is 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 >> and 2>>.
Ubuntu 24.04
Loading…