Skip to main content

Redirect

Shell redirection changes where a command reads input from and writes output to. The operators > and >> write stdout to a file, < reads stdin from a file, and 2> captures stderr.

Understanding Linux Redirection

What Is Redirection in Linux?

Every process has three standard streams: stdin (FD 0), stdout (FD 1), and stderr (FD 2). By default they use the terminal. Redirection repoints them at files, devices, or other commands, so you can save output, silence noise, or feed a file in as input.

TEXT
command > file.txt FD 1 now points at file.txt
command 2> err.txt FD 2 now points at err.txt
command 2>&1 FD 2 points wherever FD 1 points right now

Redirection Operators Reference

Bash
command > out.txt # overwrite stdout into a file
command >> out.txt # append
command 2> errors.txt # stderr to a file
command > all.txt 2>&1 # both streams to one file
command &> all.txt # bash shorthand for the line above
command > /dev/null # discard stdout
command > /dev/null 2>&1 # discard everything
command < input.txt # read stdin from a file
grep pattern <<< "text here" # here-string
cat << 'EOF' # here-document
line 1
line 2
EOF

Practical Redirection Patterns

Bash
# Log script output and watch it live
./deploy.sh 2>&1 | tee /var/log/deploy-$(date +%Y%m%d).log
# Separate logs
./build.sh > build.log 2> build-errors.log
# Hide permission errors
find / -name 'config.yaml' 2>/dev/null
# Read a file line by line
while IFS= read -r line; do
echo "Processing: $line"
done < /etc/hosts
# Write to a root-owned file
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.d/99-custom.conf

Troubleshooting Redirection

Symptom Command What to Check
Errors not captured Add 2>&1 Only stdout redirected
sudo echo fails to write Use sudo tee Shell opens file first
Both streams still on screen Check order 2>&1 placed before >
Common Mistake

Writing command 2>&1 > file. Redirections run left to right, so stderr is pointed at the terminal first and only stdout goes to the file. Write command > file 2>&1.

Tip

sudo echo x >> /etc/file fails because your shell opens the file before sudo runs. echo x | sudo tee -a /etc/file works because tee itself runs as root.

Security

> truncates the file with no confirmation. In scripts, set -o noclobber makes > refuse to overwrite an existing file unless you force it with >|.

Frequently Asked Questions

Why does command > file 2>&1 differ from command 2>&1 > file?

Redirections are processed left to right and `2>&1` copies where FD 1 points at that moment. In the first form stdout already points at the file, so stderr follows it. In the second, stderr copies the terminal before stdout moves to the file.

How do I append instead of overwrite?

Use `>>`. A single `>` truncates the file to zero length before writing.

What does /dev/null do?

It is a special device that discards everything written to it. Redirecting output there silences it.

Found a mistake, an outdated step or a broken link?