Redirection Operators
In this page:
Writing and Overwriting with >
The > operator sends a command's stdout to a file, creating it if needed and completely truncating it if it already exists. Every run of the same > command wipes out the previous contents.
Warning: > destroys existing file contents instantly with no confirmation.
Example: Writing and Overwriting with >
#!/bin/bash
echo "first line" > out.txt
echo "second run overwrites" > out.txt
cat out.txt
rm -f out.txt
Login to try C/C++/Java/PHP code in the editor
Appending with >>
The >> operator appends output to the end of a file instead of truncating it, creating the file if it does not already exist. This is the safe choice for log files that should accumulate over time.
Example: Appending with >>
#!/bin/bash
echo "line 1" > log.txt
echo "line 2" >> log.txt
echo "line 3" >> log.txt
cat log.txt
rm -f log.txt
Login to try C/C++/Java/PHP code in the editor
Reading Input from a File with <
The < operator redirects a file's contents to a command's stdin, as though the file's text had been typed. This works with any command that reads from stdin, including read and cat.
Example: Reading Input from a File with <
#!/bin/bash
echo "data from a file" > input.txt
read -r line < input.txt
echo "Read: $line"
rm -f input.txt
Login to try C/C++/Java/PHP code in the editor
Redirecting stderr and Combining Streams
2> sends only stderr to a file, leaving stdout untouched. &> (or > file 2>&1) sends both streams to the same destination, which is convenient for capturing everything a command produces.
Note: &> is a bash extension; POSIX sh scripts should use > file 2>&1 instead.
Example: Redirecting stderr and Combining Streams
#!/bin/bash
ls not_a_real_file 2> errors.txt
echo "stderr captured:"
cat errors.txt
rm -f errors.txt
{ echo out; echo err >&2; } &> combined.txt
echo "combined captured:"
cat combined.txt
rm -f combined.txt
Login to try C/C++/Java/PHP code in the editor
- Using
>when you meant>>and accidentally erasing a file's previous contents. - Forgetting that
2>only redirects stderr, so stdout still prints to the screen unless it is redirected too. - Believing
< filesomehow changes what a command outputs; it only changes where the command reads its input from.
>truncates and writes;>>appends without erasing existing content.<redirects a file's contents to a command's stdin.2>redirects stderr only;2>&1merges stderr into wherever stdout currently points.&>file(bash-specific) redirects both stdout and stderr tofilein one step.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null