What does outputting to /dev/null accomplish in bash scripts?
Oftentimes I run into small bash scripts that use this sort of syntax in if statements:
some command > /dev/null 2>&1
What is the purpose of outputting to
/dev/null like that, and what does the
It always seems to work but I’d like to know what it’s doing.
>/dev/null redirects the command standard output to the null device, which is a special device which discards the information written to it
2>&1 redirects the standard error stream to the standard output stream (stderr = 2, stdout = 1). Note that this takes the standard error stream and points it to same location as standard output at that moment. This is the reason for the order
>/some/where 2>&1 because one needs to first point stdout to somewhere and then point stderr to the same location if one wants to combine both streams in the end.
In practice it prevents any output from the command (both stdout and stderr) from being displayed. It’s used when you don’t care about the command output.
STDIN is represented by 0, STDOUT by 1, and STDERR by 2.
/dev/null is the bit-bucket: the place where you dump anything you don’t need.
So, the STDOUT is redirected to the bit-bucket(trash) and the STDERR is redirected to where the STDOUT is located: the bit-bucket.
You can also do this: