bash redirect stderr to stdout — 2>&1 and &>
Quick Answer
# Redirect stderr to stdout (combine both streams)
command 2>&1
# Redirect both stdout and stderr to a file
command > output.log 2>&1
# Short form (bash 4+)
command &> output.log
# Suppress all output (stdout + stderr)
command &> /dev/null
Usage
Stderr is separate from stdout. If you pipe a command, error messages are not captured unless you redirect stderr.
Other causes & fixes
Order matters — 2>&1 must come after >
# CORRECT — redirect stdout to file, then stderr to wherever stdout goes
command > file.log 2>&1
# WRONG — redirects stderr to the terminal (original stdout), then stdout to file
command 2>&1 > file.log
Capture only stderr (discard stdout)
# Redirect stdout to /dev/null, keep stderr visible
command 2>&1 1>/dev/null
# Short: redirect stdout to /dev/null, stderr to stdout
command 1>/dev/null
Append both streams to a log file
command >> output.log 2>&1
Capture command output into a variable
output=$(command 2>&1)
echo "Got: $output"
Pipe both output streams into another command
A pipe normally forwards stdout only. Put 2>&1 on the command before the pipe when stderr should be processed too.
# Send stdout and stderr to grep
command 2>&1 | grep -i "error"
# Keep the pipeline status meaningful when an earlier command fails
set -o pipefail
Keep stdout and stderr in separate files
Use separate file descriptors when a log consumer needs normal output and errors independently.
command > output.log 2> error.log
# Append instead of replacing existing logs
command >> output.log 2>> error.log
Related