Silencing All Output of a Command in POSIX shell
It's often useful to test the exit codes of commands to make decisions. For example,
if command -v vi; then
printf 'vi is installed\n'
fi
A problem here is that the command, like in this example, may output lines to STDOUT
and STDERR
, which is usually not what we want.
To silence STDOUT
, we can redirect it to /dev/null
, the null device.
command -v vi >/dev/null
We could do the same for STDERR
, but it's idiomatic to redirect STDERR
to STDOUT
instead, thereby redirecting both outputs to /dev/null
. This is done using the >&
redirection operator.
[n]>&[m]
This works by making file descriptor n
a copy of file descriptor m
. In other words, all output sent to n
is redirected to m
.
The example then becomes
if command -v vi >/dev/null 2>&1; then
printf 'vi is installed\n'
fi
The Open Group Base Specifications Issue 8 (2.7.6 Duplicating an Output File Descriptor)