Bash Redirection
Redirection sends output to a file instead of the screen. It can also send a file into a command as input.
Write to a file
The > operator writes the echo output into notes.txt. The cat command prints the contents of a file.
echo "first line" > notes.txt
cat notes.txtAppend to a file
The >> operator adds a line at the end. Both lines stay in the file.
echo "first line" > notes.txt
echo "second line" >> notes.txt
cat notes.txtFeed a file to a command
The wc -l command counts lines in its input. The < operator feeds the file into wc.
echo "first line" > notes.txt
echo "second line" >> notes.txt
echo "third line" >> notes.txt
wc -l < notes.txtExample
cat missing.txt 2> err.txt
echo "the script kept running"
cat err.txtKey points
- The > operator writes output into a file.
- Writing with > replaces the old content of a file.
- The >> operator adds output at the end of a file.
- Use cat to print the contents of a file.
- The < operator feeds a file into a command as input.
- The 2> operator sends error messages into a file.
In this example, cat tries to print a file that does not exist. The 2> operator sends its error message into err.txt instead of the screen. The script keeps running, and the last cat prints the saved error.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which operator adds output at the end of a file?