Reputation: 159
I have a question for redirection.
I always use anycommands > /dev/null 2>&1
when I need not any output. But I have never used anycommands 2> /dev/null >&2
Question: Which one is the best way to expect no outputs? What's the difference between anycommands > /dev/null 2>&1
and anycommands 2> /dev/null >&2
Upvotes: 2
Views: 2783
Reputation: 212248
Effectively, the two are equivalent. cmd > /dev/null 2>&1
connects stdout of the command to /dev/null
, and then connects stderr to the same file. cmd 2>/dev/null >&2
connects stderr to /dev/null
, and then connects stdout to it. The only difference is in the order in which the two streams are associated with /dev/null
, which has no bearing on the status of the command when it is run. In both cases, both streams are redirected to the bit bucket.
Upvotes: 1
Reputation: 1808
case#1:(echo stdout;echo stderr>&2) >/dev/null 2>&1
/dev/null
&1
which now is an fd to /dev/null
case#2:(echo stdout;echo stderr>&2) 2>&1 >/dev/null
&1
which is the default stdout/dev/null
stderr
is empty, stdout
not shown, stderr
on stdout
case#3: (echo stdout; echo stderr >&2) 2> /dev/null >&2
same as case#1, stderr
and stdout
have switched roles
Upvotes: 2
Reputation: 328614
If you're using only BASH, use &>
to redirect both stdout and stderr. That's the most compact, safe and simple solution.
Regarding your question, the first one is equivalent to &>
(it redirects both stdout and stderr to /dev/null
.
The second connects stderr to /dev/null
and redirects stdout to the new stderr, so it's equivalent to as far as the output is concerned. Just the order of file descriptor operations is reversed.
Upvotes: -1