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.
command > file.txt FD 1 now points at file.txtcommand 2> err.txt FD 2 now points at err.txtcommand 2>&1 FD 2 points wherever FD 1 points right nowRedirection Operators Reference
command > out.txt # overwrite stdout into a filecommand >> out.txt # appendcommand 2> errors.txt # stderr to a filecommand > all.txt 2>&1 # both streams to one filecommand &> all.txt # bash shorthand for the line abovecommand > /dev/null # discard stdoutcommand > /dev/null 2>&1 # discard everythingcommand < input.txt # read stdin from a file grep pattern <<< "text here" # here-stringcat << 'EOF' # here-documentline 1line 2EOFPractical Redirection Patterns
# 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 errorsfind / -name 'config.yaml' 2>/dev/null # Read a file line by linewhile IFS= read -r line; do echo "Processing: $line"done < /etc/hosts # Write to a root-owned fileecho 'vm.swappiness=10' | sudo tee -a /etc/sysctl.d/99-custom.confTroubleshooting 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 MistakeWriting
command 2>&1 > file. Redirections run left to right, so stderr is pointed at the terminal first and only stdout goes to the file. Writecommand > file 2>&1.
Tip
sudo echo x >> /etc/filefails because your shell opens the file before sudo runs.echo x | sudo tee -a /etc/fileworks because tee itself runs as root.
Security
>truncates the file with no confirmation. In scripts,set -o noclobbermakes>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.