Output Redirection
Redirection sends output to a file instead of the screen. Standard output is where a command normally prints its words.
Save output in a file
> sends the words to hello.txt. cat shows the file holds them.
$ cd ~/practice
$ echo hello > hello.txt
$ cat hello.txtWrite many lines at once
A heredoc sends lines to cat until EOF. cat writes them to greet.txt.
$ cd ~/practice
$ cat > greet.txt <<EOF
Hello there
Goodbye for now
EOF
$ cat greet.txtCatch the error in a file
ls cannot find missing.txt. 2> sends the error to errors.txt, and cat shows it.
$ cd ~/practice
$ ls missing.txt 2> errors.txt
$ cat errors.txtExample
$ cd ~/practice
$ echo done > note.txt
$ cat note.txt
$ ls nope.txt 2> err.txt
$ cat err.txtKey points
- Use > to send standard output to a file.
- Standard input is where a command reads from.
- Standard error is where a command prints its errors.
- Use 2> to send standard error to a file.
- A heredoc feeds many lines to a command at once.
- Redirection never changes the command. It only changes where the words go.
In this example, echo writes done to note.txt. cat reads the file back. ls fails on nope.txt, and 2> sends the error to err.txt. cat shows the error from the file.
Note
Errors still print on the screen when only standard output is sent to a file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the greater-than sign do?