如何标准输出+标准错误重定向到一个文件,同时保持流分开? [英] How to redirect stdout+stderr to one file while keeping streams separate?

查看:676
本文介绍了如何标准输出+标准错误重定向到一个文件,同时保持流分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重定向标准输出+标准错误,这样既得到写入文件,同时还输出到标准输出是很简单的:

Redirecting stdout+stderr such that both get written to a file while still outputting to stdout is simple enough:

cmd 2>&1 | tee output_file

不过,那么现在从CMD标准输出/标准错误都在标准输出来了。我想写标准输出+标准错误输出到同一个文件(所以排序是preserved假设cmd是单线程的),但是仍然能够还分别对它们进行重定向,像这样:

But then now both stdout/stderr from cmd are coming on stdout. I'd like to write stdout+stderr to the same file (so ordering is preserved assuming cmd is single threaded) but then still be able to also separately redirect them, something like this:

some_magic_tee_variant combined_output cmd > >(command-expecting-stdout) 2> >(command-expecting-stderr)

所以combined_output包含都与秩序preserved,但命令期望,标准输出只得到stdout和命令期望,标准错误只获取标准错误。基本上,我要记录标准输出+标准错误,同时仍允许输出和错误单独重定向和管道。与三通方法的问题是它的水珠在一起。有没有办法在bash做到这一点/ zsh的?

So combined_output contains the both with order preserved, but the command-expecting-stdout only gets stdout and command-expecting-stderr only gets stderr. Basically, I want to log stdout+stderr while still allowing stdout and stderr to be separately redirected and piped. The problem with the tee approach is it globs them together. Is there a way to do this in bash/zsh?

推荐答案

从我unterstand这是你在找什么。首先,我做了一个豆蔻脚本的输出和错误写。它看起来是这样的:

From what I unterstand this is what you are looking for. First I made a litte script to write on stdout and stderr. It looks like this:

$ cat foo.sh 
#!/bin/bash

echo foo 1>&2
echo bar

然后我跑这样的:

Then I ran it like this:

$ ./foo.sh 2> >(tee stderr | tee -a combined) 1> >(tee stdout | tee -a combined)
foo
bar

在结果我的庆典是这样的:

$ cat stderr
foo
$ cat stdout 
bar
$ cat combined 
foo
bar

请注意所需-a标志,让 T恤 s切勿覆盖其他 T恤的内容。

Note that the -a flag is required so the tees don't overwrite the other tee's content.

这篇关于如何标准输出+标准错误重定向到一个文件,同时保持流分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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