Saving Output to Files: > and >>

Output goes to the screen, unless you redirect it

Everything a command prints, like the list from ls, goes to its standard output (stdout for short). Normally that's your terminal. With > you can send it into a file instead:

echo "Hello, file" > hello.txt
cat hello.txt

In the terminal

student@vulntech:~$ echo "Hello, file" > hello.txt
student@vulntech:~$ cat hello.txt
Hello, file

Nothing appeared after the first command: the text went into hello.txt. If the file doesn't exist, > creates it.

It works with any command. Save the list of everything in /etc, then look at the file:

ls /etc > etc-list.txt
wc -l etc-list.txt
head -n 3 etc-list.txt

In the terminal

student@vulntech:~$ ls /etc > etc-list.txt
student@vulntech:~$ wc -l etc-list.txt
64 etc-list.txt
student@vulntech:~$ head -n 3 etc-list.txt
acpi
alpine-release
apk

> replaces the file

A single > replaces whatever was in the file:

echo first > note.txt
echo second > note.txt
cat note.txt

In the terminal

student@vulntech:~$ echo first > note.txt
student@vulntech:~$ echo second > note.txt
student@vulntech:~$ cat note.txt
second

>> adds to the end

Two arrows, >>, append: the new output goes after what's already there. This is how log files grow:

echo "08:00 left the harbour" >> journal.txt
echo "12:30 dolphins spotted" >> journal.txt
cat journal.txt

In the terminal

student@vulntech:~$ echo "08:00 left the harbour" >> journal.txt
student@vulntech:~$ echo "12:30 dolphins spotted" >> journal.txt
student@vulntech:~$ cat journal.txt
08:00 left the harbour
12:30 dolphins spotted
You typeWhat happensWhat was in the file
command > fileThe output is saved in fileLost, replaced by the output
command >> fileThe output is added at the end of fileKept

Common mistake: Never redirect into the file you're reading. The shell empties names.txt before sort starts, so sort reads an empty file and the names are gone:

sort names.txt > names.txt
wc -l names.txt

In the terminal

student@vulntech:~$ sort names.txt > names.txt
student@vulntech:~$ wc -l names.txt
0 names.txt

Write to a new file instead (sort names.txt > sorted.txt).

Tip: Afraid of overwriting something? set -o noclobber makes > refuse to replace an existing file, and >| forces it when you really mean it. set +o noclobber turns the protection off again.

set -o noclobber
echo again > note.txt
echo again >| note.txt
cat note.txt
set +o noclobber

In the terminal

student@vulntech:~$ set -o noclobber
student@vulntech:~$ echo again > note.txt
-bash: note.txt: cannot overwrite existing file
student@vulntech:~$ echo again >| note.txt
student@vulntech:~$ cat note.txt
again
student@vulntech:~$ set +o noclobber

Remember: > saves output in a file, replacing it. >> adds to the end.

HOME LEARN COMMUNITY DASHBOARD
Practice terminal Starting…