Bash Shell Redirects
Luke Hebert
- 2 minutes read - 369 wordsShell redirects let you control where command output goes. Instead of everything landing on your terminal, you can write stdout or stderr to a file, swap the two streams, or combine them. Here is a compact reference for the operators you will reach for most often.
Redirect stdout to a file
command > output.txtThe single > operator sends standard output (file descriptor 1) to the named file. If the file already exists, its contents are overwritten.
Append stdout to a file
command >> output.txtThe double >> operator does the same thing as > but appends to the file instead of truncating it. Handy for logging over time.
Redirect stderr to stdout
command 2>&1File descriptor 2 is stderr. The 2>&1 syntax points stderr to wherever stdout is currently going. Combined with a file redirect, you capture both streams:
command > output.txt 2>&1Redirect stdout to stderr
command 1>&2The reverse of the previous case. stdout is sent to the stderr stream. Useful when a parent process is capturing stderr and you want stdout to follow.
Redirect stderr to a file
command 2> errors.logSends only stderr to the named file while stdout continues to the terminal.
Redirect stdout to a file
command 1> output.txtExplicit form of the > operator. You rarely need to write 1> because stdout is the default, but it makes the intent clear in scripts.
Quick reference table
| Operator | Meaning |
|---|---|
> | stdout to file (overwrite) |
>> | stdout to file (append) |
2>&1 | stderr to wherever stdout is going |
1>&2 | stdout to wherever stderr is going |
2> | stderr to file |
1> | stdout to file (explicit) |
A few practical tips
- Order matters.
command > out.txt 2>&1captures both streams intoout.txt. Swapping tocommand 2>&1 > out.txtsends stderr to the terminal and only stdout to the file. - Use
>>in cron jobs and long-running scripts so you do not lose earlier log entries. - If you want to discard output entirely, redirect to
/dev/null:command > /dev/null 2>&1.
These six operators cover the vast majority of day-to-day shell scripting. Once the file-descriptor model clicks, the rest of bash redirection (process substitution, here-docs, tee) builds naturally on top of them.