如何获取标准输出和STDERR转到终端和日志文件? [英] How do I get both STDOUT and STDERR to go to the terminal and a log file?

查看:1063
本文介绍了如何获取标准输出和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.

我希望同时输出和错误重定向到终端(使得用户可以看到该脚本工作以及看看是否有一个问题)。我也想重定向到一个日志文件,这两个流。

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.

的完美解决方案将是code可能被掺入发送两个流到终端以及日志文件中的任何脚本的开始的一行上。

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和管道的结果发球作品,但它取决于用户记忆重定向和管道输出。我想记录是傻瓜型和自动(这就是为什么我希望能够嵌入溶液注入脚本本身。)

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.)

推荐答案

更​​新:我所有的答案,结合到一个

Update: Combining all my answers into one

使用三通,以重定向到文件和屏幕。根据您使用的shell,你首先要重定向标准错误使用到stdout

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,有被称为脚本,将捕获该进到屏幕到文件一切内置命令。通过键入脚本,然后做什么是你想要捕捉启动它,然后点击控制-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 now 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

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

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