bash 将标准输出复制到标准错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3141738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:16:27  来源:igfitidea点击:

Duplicating stdout to stderr

bashredirect

提问by Cristiano Paris

I'd like to have the stdout of a command replicated to stderr as well under bash. Something like:

我希望将命令的标准输出复制到标准错误以及 bash 下。就像是:

$ echo "FooBar" (...)
FooBar
FooBar
$

where (...) is the redirection expression. Is that possible?

其中 (...) 是重定向表达式。那可能吗?

回答by marco

Use tee with /dev/stderr:

将 tee 与 /dev/stderr 一起使用:

echo "FooBar" | tee /dev/stderr

or use awk/perl/python to manually do the replication:

或使用 awk/perl/python 手动进行复制:

echo "FooBar" | awk '{print;print > "/dev/stderr"}'

echo "FooBar" | perl -pe "print STDERR, $_;"

回答by brablc

Use process substitution: http://tldp.org/LDP/abs/html/process-sub.html

使用进程替换:http: //tldp.org/LDP/abs/html/process-sub.html

echo "FooBar" | tee >(cat >&2)

echo "FooBar" | tee >(cat >&2)

Tee takes a filename as parameter and duplicates output to this file. With process substitution you can use a process instead of filename >(cat)and you can redirect the output from this process to stderr >(cat >&2).

Tee 将文件名作为参数并将输出复制到此文件。通过进程替换,您可以使用进程而不是文件名,>(cat)并且可以将此进程的输出重定向到 stderr >(cat >&2)

回答by u890106

If I may expand @defdefred's answer, for multiple lines I'm using

如果我可以扩展@defdefred 的答案,对于我正在使用的多行

my_commmand | while read line; do echo $line; echo $line >&2; done

It has the "advantage" of not requiring / calling teeand using built-ins.

它具有不需要/调用tee和使用内置函数的“优势” 。

回答by defdefred

echo "FooBar" |tee /dev/stderr
tee: /dev/stderr: Permission denied

not working with RedHat 6.3

不适用于 RedHat 6.3

echo "FooBar" | ( read A ; echo $A ; echo $A >&2)

is working

正在工作

回答by mouviciel

For redirecting to stderr, I would use >&2or >/dev/stderr. For replicating output, I would use tee. The drawback of it is that a temporary file is needed:

为了重定向到 stderr,我会使用>&2or >/dev/stderr。对于复制输出,我会使用tee. 它的缺点是需要一个临时文件:

echo "FooBar" | tee /tmp/stdout >&2 ; cat /tmp/stdout