Shell Redirection
Redirection sends the output of a command into a file. The shell sends output to the screen unless redirection points it elsewhere.
Send output to a file
echo writes its words into list.txt instead of the screen.
echo "Buy bread" > list.txt
cat list.txtReplace the file
A second > writes over the file, so only the new line stays.
echo "Buy bread" > list.txt
echo "Buy milk" > list.txt
cat list.txtAppend to the file
>> adds the new line after the old lines.
echo "Buy bread" > list.txt
echo "Buy milk" >> list.txt
cat list.txtFeed a file in
< feeds notes.txt in as the input of grep.
grep Ana < notes.txtExample
echo "Buy milk" > list.txt
echo "Call Ana" >> list.txt
echo "Book train tickets" >> list.txt
cat list.txtKey points
- Use > to send output into a file.
- Use >> to add output to the end of a file.
- Use < to feed a file in as the input of a command.
- Redirection creates the file when it does not exist yet.
- A second > replaces the whole file, so the old text is gone.
In this example, the first echo creates list.txt with one line. The next two echoes append one line each. Then cat prints the whole file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does >> do?