AkihikoTakahashi
AkihikoTakahashi

Reputation: 159

What's the difference between ">/dev/null 2>&1" and "2>/dev/null >&2"

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

Answers (3)

William Pursell
William Pursell

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

Zoltán Haindrich
Zoltán Haindrich

Reputation: 1808

case#1:(echo stdout;echo stderr>&2) >/dev/null 2>&1

  • stdout(1) is replaced by an fd to /dev/null
  • stderr(2) descriptor is copied from &1 which now is an fd to /dev/null
  • result: no output at all

case#2:(echo stdout;echo stderr>&2) 2>&1 >/dev/null

  • stderr(2) descriptor is copied from &1 which is the default stdout
  • stdout(1) is replaced by an fd to /dev/null
  • result: 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

Aaron Digulla
Aaron Digulla

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

Related Questions