简体   繁体   English

将bash stderr发送到日志文件,但仅当存在错误时

[英]send bash stderr to logfile, but only if an error exists

I am using the following code to send stderr to a file. 我正在使用以下代码将stderr发送到文件。

.script >2 "errorlog.$(date)"

The problem is that a blank log file is created every time I run the script, even if an error doesn't exist. 问题是即使我不运行错误,每次运行脚本时也会创建一个空白日志文件。 I have looked online and in a few books as well, and can't figure out how to create a log file only if errors exist. 我在网上和几本书中都看过,并且仅在存在错误的情况下才想出如何创建日志文件。

Output redirection opens the file before the script is run, so there is no way to tell if the file will receive any output. 输出重定向会在脚本运行之前打开文件,因此无法判断文件是否将接收任何输出。 What you can do, however, is immediately delete the file if it winds up being empty: 但是,您可以做的是,如果发现文件为空,则立即删除该文件:

logfile="errorlog.$(date)"
# Note your typo; it's 2>, not >2
script 2> "$logfile"; [ -s "$logfile" ] || rm -f "$logfile"

I use -f just in case, as -s can fail if $logfile does not exist, not just if it's empty. 我使用-f只是为了以防万一,因为-s$logfile不存在的情况下会失败,而不仅仅是它为空。 I use ; 我用; to separate the commands because whether or not $logfile contains anything does not depend on whether or not script succeeds. 分隔命令,因为$logfile是否包含任何内容并不取决于script是否成功。

You can wrap this up in a function to make it easier to use. 您可以将其包装在一个函数中以使其更易于使用。

save_log () {
    logfile=${1:-errorlog.$(date)}
    cat - > "$logfile"
    [ -s "$logfile" ] || rm -f "$logfile"
}

script 2> >( save_log )
script 2> >( save_log my_logfile.txt )

Not quite as simple as redirecting to a file, and depends on a non-standard feature (process substitution), but not too bad, either. 它不像重定向到文件那样简单,并且依赖于非标准功能(进程替换),但是也不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM