2>&1 will redirect stderr to wherever stdout currently points to. The argument
>/dev/null will redirect stdout to
/dev/null i.e discard/silent the output by command. But if you also want to discard (make silent) the stderr, then after redirecting stdout to
2>&1 to redirect stderr to the same place.
Example (For visualizing difference):
$ ls file1 > /dev/null
Here the output of
ls file1 is
file1 which is sent to
/dev/null and hence we get nothing. But:
$ ls file12 > /dev/null
ls: cannot access file12: No such file or directory
which gives stderr and as only output is sent to
/dev/null. So, If you want to discard/silent stderr also then you can redirect stderr to stdout and hence both will be sent to
/dev/null as follows:
$ ls file12 >/dev/null 2>&1
Note that the order/sequence of redirection matters.
2>&1 to redirect standard error must always be placed after redirecting standard output or it doesn't do anything. In above example if you run
ls file12 2>&1 >/dev/null you will see the stderr printed to the terminal; if you run
ls file12 >/dev/null 2>&1 you won't.
- Alternatively You could also use
ls file1 file12 2>/dev/null 1>&2 with the same effect—which first redirects stderr to
/dev/null and then redirects stdout to point to the same place stderr is currently pointing to.
- With the new version of bash you can also use
>& simply like:
ls file12 >& /dev/null which will redirects both stdout & stderr to