将 stdout 和 stderr 重定向到文件,将 stderr 重定向到屏幕,同时保留输出顺序 [英] redirect stdout and stderr to file and stderr to screen while preserving output order

查看:63
本文介绍了将 stdout 和 stderr 重定向到文件,将 stderr 重定向到屏幕,同时保留输出顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 stdout 和 stderr 重定向到一个文件,同时保留输出顺序,但同时也将 stderr 显示到屏幕上.我看到很多问题都在讨论它:

I want to redirect stdout and stderr to a file while preserving the order of output but then also show stderr to screen. I see a lot of questions discuss it:

但他们似乎都没有做我想做的事或保留订单.

But none of them seem to do what I want or preserve the order.

我的测试脚本:

#!/bin/bash

echo "1: good" >&1
echo "2: error" >&2
echo "3: error" >&2
echo "4: good" >&1
echo "5: error" >&2
echo "6: good" >&1
echo "7: error" >&2
echo "8: good" >&1
echo "9: error" >&2

到目前为止我所拥有的:

What I have so far:

$ ./test.sh 2>&1 > output.log

推荐答案

标准 UNIX 语义不允许这样做;不能仅使用内置于 bash 中或在 POSIX 中指定的工具来可靠地完成.

Standard UNIX semantics do not permit this; it cannot be reliably done using only facilities built into bash or specified in POSIX.

当写入发生在同一目的地时,写入之间只有一个有保证的顺序.一旦您将 stdout 和 stderr 重定向到不同的目的地,操作系统就不再保证对它们执行的写入顺序;当这些写入是到一个单独的进程(例如 tee)时,该进程必须读取内容并执行自己的进一步写入,受操作系统级调度的约束.

Writes only have a guaranteed order in relation to each other when they happen to the same destination. As soon as you redirect stdout and stderr to different destinations, the operating system no longer offers guarantees around ordering of writes performed to them; doubly when those writes are to a separate process (such as tee) which then must read content and perform its own further writes, subject to OS-level scheduling.

可以使用操作系统提供(或可用于)的系统调用级跟踪工具来生成系统调用的绝对顺序,从而生成明确排序的输出;单独重定向和重新组合的答案中给出了一个例子stderr/stdout 不会丢失顺序.

It may be possible to use syscall-level tracing facilities provided by (or available for) your operating system to generate an absolute ordering of system calls, and thus to generate definitively-ordered output; an example of this is given in the answer to Separately redirecting and recombining stderr/stdout without losing ordering.

但是,使用 bash 本身,您只能控制子进程的文件描述符的连接位置,而不能控制写入这些描述符的内容如何缓冲和刷新,因此根本没有足够的控制来实现您的要求可能不会对写入进行重新排序.

Using bash itself, however, you can only control where file descriptors of a subprocess are connected, and not how content written to those descriptors is buffered and flushed, so there simply isn't enough control to make what you're asking for possible without writes being subject to reordering.

这篇关于将 stdout 和 stderr 重定向到文件,将 stderr 重定向到屏幕,同时保留输出顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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