IO Redirection - Swapping stdout and stderr

后端 未结 4 783
借酒劲吻你
借酒劲吻你 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条回答
  •  Happy的楠姐
    2020-12-05 10:20

    % (sh myscript.sh 3>&2 2>&1 1>&3) 2>/dev/null
    I'm stderr
    % (sh myscript.sh 3>&2 2>&1 1>&3) >/dev/null 
    I'm stdout
    

    Explanation of 3>&2 2>&1 1>&3:

    • 3>&2 means make a copy of file descriptor 2 (fd 2) (stderr), named fd 3 (file descriptor 3). It copies the file descriptor, it doesn't duplicate the stream as tee does.
    • 2>&1 means that fd 2 of sh myscript.sh becomes a copy of it's fd 1 (stdout). Now, when myscript writes to it's stderr (it's fd 2), we receive it on stdout (our fd 1).
    • 1>&3 means that fd 1 of sh myscript.sh becomes a copy of fd 3 (stderr). Now, when myscript writes to it's stdout (it's fd 1), we receive it on stderr (our fd 2).

提交回复
热议问题