如何让 STDOUT 和 STDERR 都转到终端和日志文件? [英] How do I get both STDOUT and STDERR to go to the terminal and a log file?

查看:22
本文介绍了如何让 STDOUT 和 STDERR 都转到终端和日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将由非技术用户交互运行的脚本.脚本将状态更新写入 STDOUT,以便用户可以确定脚本运行正常.

I have a script which will be run interactively by non-technical users. The script writes status updates to STDOUT so that the user can be sure that the script is running OK.

我希望 STDOUT 和 STDERR 都重定向到终端(以便用户可以看到脚本正在运行以及查看是否有问题).我还希望将两个流都重定向到日志文件.

I want both STDOUT and STDERR redirected to the terminal (so that the user can see that the script is working as well as see if there was a problem). I also want both streams redirected to a log file.

我在网上看到了一堆解决方案.有些不起作用,有些则非常复杂.我已经开发了一个可行的解决方案(我将其作为答案输入),但它很笨拙.

I've seen a bunch of solutions on the net. Some don't work and others are horribly complicated. I've developed a workable solution (which I'll enter as an answer), but it's kludgy.

完美的解决方案是将一行代码合并到任何脚本的开头,该脚本将两个流发送到终端和日志文件.

The perfect solution would be a single line of code that could be incorporated into the beginning of any script that sends both streams to both the terminal and a log file.

将 STDERR 重定向到 STDOUT 并将结果通过管道传输到 tee 工作,但这取决于用户是否记得重定向和管道输出.我希望日志记录是万无一失的和自动的(这就是为什么我希望能够将解决方案嵌入到脚本本身中.)

Redirecting STDERR to STDOUT and piping the result to tee works, but it depends on the users remembering to redirect and pipe the output. I want the logging to be fool-proof and automatic (which is why I'd like to be able to embed the solution into the script itself.)

推荐答案

使用tee"重定向到文件和屏幕.根据您使用的 shell,您首先必须使用

Use "tee" to redirect to a file and the screen. Depending on the shell you use, you first have to redirect stderr to stdout using

./a.out 2>&1 | tee output

./a.out |& tee output

在 csh 中,有一个名为script"的内置命令,可以将进入屏幕的所有内容捕获到文件中.您通过键入脚本"开始它,然后执行您想要捕获的任何操作,然后按 control-D 关闭脚本文件.我不知道 sh/bash/ksh 的等价物.

In csh, there is a built-in command called "script" that will capture everything that goes to the screen to a file. You start it by typing "script", then doing whatever it is you want to capture, then hit control-D to close the script file. I don't know of an equivalent for sh/bash/ksh.

此外,由于您已指出这些是您自己的 sh 脚本,您可以修改这些脚本,因此您可以通过用大括号或方括号将整个脚本括起来来在内部进行重定向,例如

Also, since you have indicated that these are your own sh scripts that you can modify, you can do the redirection internally by surrounding the whole script with braces or brackets, like

  #!/bin/sh
  {
    ... whatever you had in your script before
  } 2>&1 | tee output.file

这篇关于如何让 STDOUT 和 STDERR 都转到终端和日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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