6

I would like to prevent my program from sending stdout and stderr to any terminals, files or devices. For this, I have three command crossing my mind, but I cannot distinguish their differences. Could you please explain the meaning of each of them to me please.

# ./run > /dev/null
# ./run > /dev/null 1>&2
# ./run > /dev/null 2>&1
Saman
  • 371

1 Answers1

17
# ./run > /dev/null

This redirects stdout to /dev/null, but it doesn't do anything at all with stderr. Since you asked to redirect from stdout and stderr, this does not do what you want.

# ./run > /dev/null 1>&2

This redirects stdout to /dev/null, and then it redirects stdout again (1>) to wherever stderr points to (&2) which is probably the terminal and is probably where stdout pointed to before you redirected it. So the net effect here is (probably) no redirections at all for stdout, and as for stderr, you still don't do anything with it. So this is also not what you want.

# ./run > /dev/null 2>&1

This redirects stdout to /dev/null, and then it redirects stderr (2>) to wherever stdout points to, which is /dev/null because that's where you just redirected it. This seems to be what you want.

I cannot distinguish their differences.

Actually, you should be able to distinguish the differences quite easily. Let's say ./run contains this:

#!/bin/sh
echo stdout
echo stderr >&2

Then the results should be as follows:

# ./run > /dev/null
stderr
# ./run > /dev/null 1>&2
stdout
stderr
# ./run > /dev/null 2>&1

The difference is clear!

Evgeny
  • 5,476
Celada
  • 44,132