Search code examples
linuxnullcommandline

When do we use of "2>&1" in practice?


As far as I understand, "/dev/null 2>&1" makes the program silent (the whole output and errors are suppressed). And what about "2>&1" without /dev/null ? For example,

ls -ld /tmp /tnt 2>&1

What the practical usage of "2>&1" without /dev/null? Does it make any sense? (It gives the exact same output as:

ls -ld /tmp /tnt )


Solution

  • It is incorrect to say that "/dev/null 2>&1" makes the program silent. In isolation, that expression is incomplete. For example, echo foo /dev/null 2>&1 Passes foo and /dev/null as arguments to echo and runs echo with its stderr stream redirected to its stdout. On the other hand, it is more common to see:

    echo foo > /dev/null 2>&1
    

    Which redirects stdout to /dev/null, and then redirects stderr to stdout (which is now /dev/null, so both streams go go /dev/null). Notice that order is significant, and echo foo 2>&1 > /dev/null will write the errors to the calling process' stdout while writing output to /dev/null.

    A common reason to use this sort of stream duplication is when you want to control where output and errors go. For example, if you want to apply a filter to stderr, you can discard the output and filter the errors with:

    cmd 2>&1 > /dev/null | sed 's/^/ERROR: /g' >&2
    

    This is a trivial example intended merely for demonstration. To apply a filter to both streams independently, you can do things like:

    { cmd 2>&1 >&3 | sed 's/^/ERROR: /' >&2; } 3>&1 | sed 's/^/OUT:   /';