bash 如何在bash中记录输出并同时在终端中看到它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3215742/
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
How to log output in bash and see it in the terminal at the same time?
提问by Kristopher Ives
I have some scripts where I need to see the output andlog the result to a file, with the simplest example being:
我有一些脚本需要查看输出并将结果记录到文件中,最简单的示例是:
$ update-client > my.log
I want to be able to see the output of the command while it's running, but also have it logged to the file. I also log stderr
, so I would want to be able to log the error stream while seeing it as well.
我希望能够在命令运行时看到命令的输出,但也希望将其记录到文件中。我也记录stderr
,所以我希望能够在看到错误流的同时记录它。
回答by Matthew Flaschen
update-client 2>&1 | tee my.log
2>&1 redirects standard error to standard output, and tee sends its standard input to standard output and the file.
2>&1 将标准错误重定向到标准输出,并且 tee 将其标准输入发送到标准输出和文件。
回答by Cfreak
Just use tail to watch the file as it's updated. Background your original process by adding & after your above command After you execute the command above just use
只需使用 tail 在文件更新时查看文件即可。通过在上面的命令之后添加 & 来背景你的原始进程执行上面的命令后,只需使用
$ tail -f my.log
It will continuously update. (note it won't tell you when the file has finished running so you can output something to the log to tell you it finished. Ctrl-c to exit tail)
它将不断更新。(请注意,它不会告诉您文件何时完成运行,因此您可以向日志输出一些内容以告诉您它已完成。Ctrl-c 退出 tail)
回答by rynop
another option is to use block based output capture from within the script (not sure if that is the correct technical term).
另一种选择是在脚本中使用基于块的输出捕获(不确定这是否是正确的技术术语)。
Example
例子
#!/bin/bash
{
echo "I will be sent to screen and file"
ls ~
} 2>&1 | tee -a /tmp/logfile.log
echo "I will be sent to just terminal"
I like to have more control and flexibility - so I prefer this way.
我喜欢有更多的控制和灵活性——所以我更喜欢这种方式。
回答by Anurag Jain
You can use the tee command for that:
您可以使用 tee 命令:
command | tee /path/to/logfile
The equivelent without writing to the shell would be:
不写入外壳的等效项是:
command > /path/to/logfile
If you want to append (>>) and show the output in the shell, use the -a option:
如果要附加 (>>) 并在 shell 中显示输出,请使用 -a 选项:
command | tee -a /path/to/logfile
Please note that the pipe will catch stdout only, errors to stderr are not processed by the pipe with tee. If you want to log errors (from stderr), use:
请注意,管道将仅捕获 stdout,带有 tee 的管道不会处理 stderr 的错误。如果要记录错误(来自 stderr),请使用:
command 2>&1 | tee /path/to/logfile
This means: run command and redirect the stderr stream (2) to stdout (1). That will be passed to the pipe with the tee application.
这意味着:运行命令并将 stderr 流 (2) 重定向到 stdout (1)。这将通过 tee 应用程序传递到管道。
Learn about this at askubuntu site
在 askubuntu 网站上了解这一点