cmd >/dev/null 2>&1 is one of those shell expressions people memorize long before they understand it. That works — until the order changes, a pipeline hides a failure, or a script runs under /bin/sh instead of Bash.
Full reference: Linux shell redirection cheatsheet
The three numbers behind the syntax
Every process starts with three conventional file descriptors:
0— stdin: input, normally the keyboard1— stdout: normal output, normally the terminal2— stderr: diagnostics, normally the terminal
The shell rewires these descriptors before it starts the command. That single model explains almost every redirection expression.
The recipes you actually need
cmd >output.log # stdout to file (overwrite)
cmd >>output.log # stdout to file (append)
cmd 2>error.log # stderr to file
cmd >output.log 2>error.log # keep them separate
cmd >combined.log 2>&1 # both to one file
cmd >/dev/null # discard stdout only
cmd 2>/dev/null # discard stderr only
cmd >/dev/null 2>&1 # discard both
/dev/null is a data sink: writes succeed and disappear. Reading it immediately returns end-of-file.
The trap: order matters
This sends both streams to the file:
cmd >combined.log 2>&1
Read it left to right: first stdout (FD 1) points to the file; then 2>&1 copies stdout's current destination onto stderr.
Reverse the order and the result changes:
cmd 2>&1 >output.log
Stderr copies stdout while stdout still points at the terminal. Then stdout moves to the file. Result: stdout is logged, stderr stays visible. 2>&1 is a snapshot of a destination, not a permanent link.
Pipes carry stdout, not stderr
cmd | less # stdout only
cmd 2>&1 | less # stdout + stderr (portable)
cmd |& less # Bash/zsh shorthand
cmd 2>&1 | tee run.log # show and save both
For Bash automation, pair pipelines with set -o pipefail. Otherwise cmd | tee run.log can report success merely because tee succeeded, even when cmd failed.
Portable shell vs convenient shell
Bash and zsh provide compact forms:
cmd &>combined.log
cmd &>>combined.log
cmd |& less
cmd <<<"one line"
But &>, |&, and here-strings aren't POSIX. If a script may run under /bin/sh, prefer >file 2>&1, 2>&1 |, and heredocs.
Good scripting habits
- Send machine-readable data to stdout and diagnostics to stderr:
printf '%s\n' "warning" >&2. - Suppress output only when the exit status is all you need:
if command -v jq >/dev/null 2>&1; then .... - Don't hide build or deployment failures with
>/dev/null 2>&1; log stderr instead. - For detached jobs, redirect all three streams:
nohup cmd >run.log 2>&1 </dev/null &. Use a service manager for real services.
The mental model worth remembering
>/<connect a descriptor to a file.n>&mcopies descriptorm's current destination ton.n>&-closes descriptorn.|connects the left process's stdout to the right process's stdin.- The shell performs all wiring from left to right before launching the command.
Once you picture file descriptors as wires, >/dev/null 2>&1 stops being punctuation and starts being readable.