How to Use Redirect in Bash: Simple Guide with Examples
In bash, you use
redirect operators like > to send output to a file, and < to take input from a file. For example, ls > file.txt saves the output of ls into file.txt instead of showing it on the screen.Syntax
Redirects in bash use special symbols to control where input and output go.
command > file: Sends standard output (normal output) tofile, overwriting it.command >> file: Appends standard output tofilewithout erasing existing content.command < file: Takes standard input (input) fromfileinstead of keyboard.command 2> file: Sends error messages (standard error) tofile.command > file 2>&1: Sends both output and errors to the samefile.
bash
command > file.txt command >> file.txt command < file.txt command 2> error.txt command > all_output.txt 2>&1
Example
This example shows how to save the list of files in the current folder to a file, then read from a file as input.
bash
# Save output of ls to files.txt
ls > files.txt
# Append a line to files.txt
echo "New file entry" >> files.txt
# Show content of files.txt
cat files.txt
# Use input redirection to count lines in files.txt
wc -l < files.txtOutput
file1.txt
file2.txt
script.sh
New file entry
4
Common Pitfalls
Beginners often overwrite files by mistake using > instead of >>. Also, mixing output and error redirection can be confusing.
Wrong: command > file.txt 2> file.txt (errors overwrite output)
Right: command > file.txt 2>&1 (both go to same file)
bash
echo "Hello" > output.txt # This overwrites output.txt ls >> output.txt # This appends to output.txt # Wrong way to redirect errors and output separately to same file ls > all.txt 2> all.txt # Correct way to redirect both output and errors to same file ls > all.txt 2>&1
Quick Reference
| Redirect Operator | Description | Example |
|---|---|---|
| > | Send output to file (overwrite) | echo Hello > file.txt |
| >> | Append output to file | echo Hello >> file.txt |
| < | Take input from file | wc -l < file.txt |
| 2> | Send error messages to file | ls /no_dir 2> error.txt |
| >& | Redirect one output to another | command > file.txt 2>&1 |
Key Takeaways
Use > to send command output to a file, overwriting its content.
Use >> to append output to an existing file without erasing it.
Use < to provide input to a command from a file instead of keyboard.
Redirect errors with 2> and combine output and errors with 2>&1.
Be careful to avoid overwriting files unintentionally when redirecting.