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.txtIn 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.txtIn 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.txtIn 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.txtIn 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 type | What happens | What was in the file |
|---|---|---|
command > file | The output is saved in file | Lost, replaced by the output |
command >> file | The output is added at the end of file | Kept |
Common mistake: Never redirect into the file you're reading. The shell empties
names.txtbeforesortstarts, sosortreads an empty file and the names are gone:
sort names.txt > names.txt
wc -l names.txtIn 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 noclobbermakes>refuse to replace an existing file, and>|forces it when you really mean it.set +o noclobberturns the protection off again.
set -o noclobber
echo again > note.txt
echo again >| note.txt
cat note.txt
set +o noclobberIn 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.