在将 STDOUT 传输到文件时捕获 STDERR 的输出 [英] Capturing the output of STDERR while piping STDOUT to a file

查看:56
本文介绍了在将 STDOUT 传输到文件时捕获 STDERR 的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当奇怪的情况.我正在尝试使用 Perl 自动备份一组 SVN 存储库.我正在使用 svnadmin dump 命令,它将转储发送到 STDOUT,并将它遇到的任何错误发送到 STDERR.

I have a rather odd situation. I'm trying to automate the backup of a collection of SVN repositories with Perl. I'm shelling out to the svnadmin dump command, which sends the dump to STDOUT, and any errors it encounters to STDERR.

我需要运行的命令将采用以下形式:

The command I need to run will be of the form:

svnadmin dump $repo -q >$backupFile

STDOUT 将转到备份文件,但是,STDERR 是我需要在 Perl 脚本中捕获的内容.

STDOUT will go to the backup file, but, STDERR is what I need to capture in my Perl script.

处理这种情况的正确方法是什么?

What's the right way to approach this kind of situation?

澄清:STDOUT 将包含 SVN 转储数据STDERR 将包含任何可能发生的错误

To clarify: STDOUT will contain the SVN Dump data STDERR will contain any errors that may happen

STDOUT 需要以文件结尾,而 STDERR 需要以 Perl 结尾.除了 STDOUT 的原始内容之外,任何东西都不能最终出现在该流中,否则转储将被破坏,我将遇到比没有备份更糟糕的事情,糟糕透了!

STDOUT needs to end up in a file, and STDERR needs to end up in Perl. At no point can ANYTHING but the original content of STDOUT end up in that stream or the dump will be corrupted and I'll have something worse than no backup at all, a bad one!

推荐答案

嗯,在 perl 中也有通用的方法来做到这一点,但是 bash 解决方案(上面让我觉得你正在寻找)是重定向stderr 首先 到标准输出,然后将标准输出重定向到一个文件.直觉上,除非您看到 bash 内部发生了什么,否则这并没有多大意义.但这有效:

Well, there are generic ways to do it within perl too, but the bash solution (which the above makes me think you're looking for) is to redirect stderr first to stdout and then redirect stdout to a file. intuitively this doesn't make a whole lot of sense until you see what's happening internally to bash. But this works:

svnadmin dump $repo -q 2>&1 >$backupFile

但是,不要以另一种方式执行(即,将 2>&1 放在最后),否则 stdout 和 stderr 的所有输出都将进入您的文件.

However, do not do it the other way (ie, put the 2>&1 at the end), or else all the output of both stdout and stderr will go to your file.

你想要的是这个:

# perl -e 'print STDERR "foo\n"; print "bar\n";' 2>&1 > /tmp/f 
foo
# cat /tmp/f
bar

特别是你不想要这个:

# perl -e 'print STDERR "foo\n"; print "bar\n";' > /tmp/f 2>&1
# cat /tmp/f
foo
bar

这篇关于在将 STDOUT 传输到文件时捕获 STDERR 的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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