bash redirect stderr to stdout — 2>&1 and &>

# 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

Stderr is separate from stdout. If you pipe a command, error messages are not captured unless you redirect stderr.

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"