IO Redirection - Swapping stdout and stderr

后端 未结 4 785
借酒劲吻你
借酒劲吻你 2020-12-05 09:31

Given a shell script:

#!/bin/sh

echo \"I\'m stdout\";
echo \"I\'m stderr\" >&2;

Is there a way to call that script such that only s

4条回答
  •  醉话见心
    2020-12-05 10:25

    The bash hackers wiki can be very useful in this kind of things. There's a way of doing it which is not mentioned among these answers, so I'll put my two cents.

    The semantics of >&N, for numeric N, means redirect to the target of the file descriptor N. The word target is important since the descriptor can change target later, but once we copied that target we don't care. That's the reason why the order in which we declare of redirection is relevant.

    So you can do it as follows:

    ./myscript.sh 2>&1 >/dev/null
    

    That means:

    1. redirect stderr to stdout's target, that is the stdout output stream. Now stderr copied stdout's target

    2. change stdout to /dev/null. This won't affect stderr, since it "copied" the target before we changed it.

    No need for a third file descriptor.

    It is interesting how I can't simply do >&-, instead of >/dev/null. This actually closes stdout, so I'm getting an error (on stderr's target, that is the actual stdout, of course :D)

    line 3: echo: write error: Bad file descriptor
    

    You can see that order is relevant by trying to swap the redirections:

    ./myscript.sh >/dev/null 2>&1
    

    This will not work, because:

    1. We set the target of stdout to /dev/null
    2. We set the target of stderr to stdout's target, that is /dev/null again.

提交回复
热议问题