patternbashModerate
Redirecting to /dev/null: suppress stdout, stderr, or both
Viewed 0 times
/dev/nullredirectstdoutstderrsuppress outputsilencefile descriptor2>&1
Problem
Developers want to silence specific output streams but use wrong redirection order or forget that 2>&1 must come after the file redirect to have effect.
Solution
# Suppress stdout only
cmd > /dev/null
# Suppress stderr only
cmd 2> /dev/null
# Suppress both
cmd > /dev/null 2>&1
# Modern shorthand (bash 4+, not POSIX)
cmd &> /dev/null
# Redirect stderr to stdout (for piping)
cmd 2>&1 | grep pattern
cmd > /dev/null
# Suppress stderr only
cmd 2> /dev/null
# Suppress both
cmd > /dev/null 2>&1
# Modern shorthand (bash 4+, not POSIX)
cmd &> /dev/null
# Redirect stderr to stdout (for piping)
cmd 2>&1 | grep pattern
Why
File descriptors are redirected left to right. '> /dev/null 2>&1' first redirects stdout to /dev/null, then redirects stderr to wherever stdout currently points (i.e., /dev/null). Reversing the order '2>&1 > /dev/null' redirects stderr to the original stdout (terminal), then redirects stdout to /dev/null.
Gotchas
- 2>&1 > /dev/null (wrong order) sends stderr to terminal and stdout to /dev/null
- &> /dev/null is bash-specific; use > /dev/null 2>&1 for POSIX compatibility
- >&2 redirects a specific command's stdout to stderr — commonly used for error messages
- echo 'error message' >&2 is the idiomatic way to print to stderr
Code Snippets
Redirection patterns to /dev/null
# Suppress all output
cmd > /dev/null 2>&1
# Only suppress errors
cmd 2> /dev/null
# Check exit code without output
if command -v jq > /dev/null 2>&1; then
echo "jq is available"
fi
# Print to stderr (error messages)
echo "Error: file not found" >&2
# Pipe stdout+stderr together
cmd 2>&1 | tee output.logContext
Suppressing unwanted output from commands in scripts
Revisions (0)
No revisions yet.