gpt4 book ai didi

linux - Shell:将标准输出重定向到/dev/null,将标准错误重定向到标准输出

转载 作者:IT老高 更新时间:2023-10-28 12:35:58 31 4
gpt4 key购买 nike

我在 cyberciti.biz 的评论中看到了这个有趣的问题.

我发现我什至找不到一种灵活的方法来使用 sh 在单行命令中执行此操作。

我对解决方案的想法是:

tmp_file=`mktemp`
(./script 2>$tmp_file >/dev/null; cat $tmp_file) | ./other-script
rm tmp_file

但是你看,这不是同步的,而且致命的是,它太丑了。

欢迎分享你的想法。 :)

最佳答案

你想要

./script 2>&1 1>/dev/null | ./other-script

这里的顺序很重要。假设 stdin (fd 0)、stdout (fd 1) 和 stderr (fd 2) 最初都连接到一个 tty,所以

0: /dev/tty, 1: /dev/tty, 2: /dev/tty

首先要设置的是管道。 other-script 的标准输入连接到管道,脚本的标准输出连接到管道,所以脚本的文件描述符到目前为止看起来像:

0: /dev/tty, 1: pipe, 2: /dev/tty

接下来,重定向发生,从左到右。 2>&1 让 fd 2 走到 fd 1 当前去的任何地方,也就是管道。

0: /dev/tty, 1: pipe, 2: pipe

最后,1>/dev/null 将 fd1 重定向到 /dev/null

0: /dev/tty, 1: /dev/null, 2: pipe

最终结果,脚本的标准输出被静音,它的标准错误通过管道发送,最终进入其他脚本的标准输入。

另见 http://bash-hackers.org/wiki/doku.php/howto/redirection_tutorial

另请注意,1>/dev/null>/dev/null

的同义词,但比 >/dev/null 更明确

关于linux - Shell:将标准输出重定向到/dev/null,将标准错误重定向到标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12027170/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com