Redirection
Objectives
By the end of this chapter, you should be able to:
- Explain what redirection is
- Explain the difference between
>,>>, and< - Use redirection to work more effectively in Terminal
๐ก Why this matters: Most Terminal output just prints to the screen and disappears. Redirection is how you capture it โ into a file, or into another command โ which is the foundation everything in the next lesson (piping) builds on.
Sending Output to a File
By default, a command’s output goes straight to your screen. Redirection lets you send it somewhere else instead โ most often, into a file. Try it with echo:
echo Hello World > hello.txt
cat hello.txt
> took the text echo would normally print and wrote it into hello.txt instead. Now run this:
echo Hello Universe > hello.txt
cat hello.txt
hello.txt now says “Hello Universe” โ the previous contents are gone. > always overwrites the whole file.
If you want to add to a file instead of replacing it, use >>:
echo Hello World >> hello.txt
cat hello.txt
Hello Universe
Hello World
That’s the whole distinction: > replaces, >> appends. This is also a fast way to drop a short note into a file without ever opening an editor.
Reading Input From a File
> and >> both send output out of a command. < goes the other direction โ it feeds a file in as input. Take sort, which prints a file’s lines alphabetically. Given a file names.txt containing:
Bob
Tom
Jim
Amy
sort names.txt prints:
Amy
Bob
Jim
Tom
Combine all three operators and you can feed a file in, sort it, and write the result straight to a new file, all in one line:
sort < names.txt > sorted.txt
That reads names.txt in as input, sorts it, and writes the result to sorted.txt โ no cat, no manual copy-paste.
Quick Reference
| Operator | Does |
|---|---|
> |
Sends output to a file, overwriting it |
>> |
Sends output to a file, appending to it |
< |
Feeds a file in as input to a command |
Try It
Redirection changes real files on disk, so run these yourself rather than in a sandbox:
- Use
>to write your name into a file calledme.txt. - Use
>>to add your favorite color as a second line, without erasing the first. - Create a file with three or four words, one per line, in any order. Use
sortwith<and>to write a sorted copy to a second file, without ever opening either file in an editor.
Recap
>overwrites a file with a command’s output;>>appends instead.<feeds a file’s contents in as input to a command.- Redirection is one-directional per operator โ you can combine
<and>on the same line to read from one file and write to another.
You’ve only used one command at a time so far. Next lesson: chaining multiple commands together with pipes.