0
0
Bash-scriptingHow-ToBeginner · 3 min read

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) to file, overwriting it.
  • command >> file: Appends standard output to file without erasing existing content.
  • command < file: Takes standard input (input) from file instead of keyboard.
  • command 2> file: Sends error messages (standard error) to file.
  • command > file 2>&1: Sends both output and errors to the same file.
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.txt
Output
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 OperatorDescriptionExample
>Send output to file (overwrite)echo Hello > file.txt
>>Append output to fileecho Hello >> file.txt
<Take input from filewc -l < file.txt
2>Send error messages to filels /no_dir 2> error.txt
>&Redirect one output to anothercommand > 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.