IO重定向-交换标准输出和标准错误 [英] IO Redirection - Swapping stdout and stderr

查看:88
本文介绍了IO重定向-交换标准输出和标准错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个shell脚本:

Given a shell script:

#!/bin/sh

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

有没有一种方法可以调用该脚本,以便当命令的最后一部分为2>/dev/null(即

Is there a way to call that script such that only stderr would print out, when the last part of the command is 2>/dev/null, ie

$ > sh myscript.sh SOME_OPTIONS_HERE 2>/dev/null
I'm stderr

或者,或者:

$ > sh myscript.sh SOME_OPTIONS_HERE >/dev/null
I'm stdout

这是一组幻灯片的结尾处的一个问题,但是经过将近一天的工作之后,我几乎可以肯定这是一种错字.旋转不起作用. 2>&-不起作用.我没主意了!

It's a question at the end of a set of lecture slides, but after nearly a day working at this, I'm nearly certain it's some sort of typo. Pivoting doesn't work. 2>&- doesn't work. I'm out of ideas!

推荐答案

% (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

3>&2 2>&1 1>&3的解释:

  • 3>&2表示制作文件描述符2(fd 2)(stderr)的副本,名为fd 3(文件描述符3).它会复制文件描述符,不会像tee那样复制流.
  • 2>&1表示sh myscript.sh的fd 2成为其fd 1(stdout)的副本.现在,当myscript写入stderr(即fd 2)时,我们会在stdout(我们的fd 1)上收到它.
  • 1>&3表示sh myscript.sh的fd 1成为fd 3(stderr)的副本.现在,当myscript将其写入stdout(即fd 1)时,我们会在stderr(我们的fd 2)上收到它.
  • 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).

这篇关于IO重定向-交换标准输出和标准错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆