将标准输出的 COPY 从 bash 脚本本身重定向到日志文件 [英] redirect COPY of stdout to log file from within bash script itself
问题描述
我知道如何将标准输出重定向到一个文件:
I know how to redirect stdout to a file:
exec > foo.log
echo test
这会将测试"放入 foo.log 文件中.
this will put the 'test' into the foo.log file.
现在我想将输出重定向到日志文件并将其保存在标准输出中
即它可以从脚本外部轻松完成:
i.e. it can be done trivially from outside the script:
script | tee foo.log
但我想在脚本本身中声明它
but I want to do declare it within the script itself
我试过了
exec | tee foo.log
但是没有用.
推荐答案
#!/usr/bin/env bash
# Redirect stdout ( > ) into a named pipe ( >() ) running "tee"
exec > >(tee -i logfile.txt)
# Without this, only stdout would be captured - i.e. your
# log file would not contain any error messages.
# SEE (and upvote) the answer by Adam Spiers, which keeps STDERR
# as a separate stream - I did not want to steal from him by simply
# adding his answer to mine.
exec 2>&1
echo "foo"
echo "bar" >&2
注意这是bash
,而不是sh
.如果您使用 sh myscript.sh
调用该脚本,您将在意外标记 '>' 附近收到类似 syntax error 的错误.
Note that this is bash
, not sh
. If you invoke the script with sh myscript.sh
, you will get an error along the lines of syntax error near unexpected token '>'
.
如果您正在使用信号陷阱,您可能需要使用 tee -i
选项来避免在出现信号时中断输出.(感谢 JamesThomasMoon1979 的评论.)
If you are working with signal traps, you might want to use the tee -i
option to avoid disruption of the output if a signal occurs. (Thanks to JamesThomasMoon1979 for the comment.)
根据是写入管道还是终端来更改其输出的工具(例如,ls
使用颜色和列化输出)将检测上述构造作为它们输出到管道的意思.
Tools that change their output depending on whether they write to a pipe or a terminal (ls
using colors and columnized output, for example) will detect the above construct as meaning that they output to a pipe.
有一些选项可以强制着色/分列(例如 ls -C --color=always
).请注意,这将导致颜色代码也被写入日志文件,使其降低可读性.
There are options to enforce the colorizing / columnizing (e.g. ls -C --color=always
). Note that this will result in the color codes being written to the logfile as well, making it less readable.
这篇关于将标准输出的 COPY 从 bash 脚本本身重定向到日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!