如何将STDERR输出重定向到稍后附加到日志文件的变量或函数?



这就是我如何尝试重定向仅STDERR输出apt到日志文件,而apt进度报告在使用log_trace()函数的终端上可见两次:

apt update 2> >(log_trace "(APT)") | while read -r line; do
if [[ $line != "All packages are up to date." ]]; then
bool_update_required=1
fi
log_trace "(APT)" <<<"$line"
done

问题是,由于每个输出行在循环中处理两次,我从log_trace()(实际上是从另一个函数__logger_core)获得自定义行前缀» (APT)打印两次:

» (APT)   » (APT)   
» (APT)   » (APT) WARNING: apt does not have a stable CLI interface. Use with caution in scripts.  
» (APT)   » (APT)   
» (APT) Reading package lists... 
» (APT)   » (APT) E: Could not get lock /var/lib/apt/lists/lock. It is held by process 1490 (packagekitd)  
» (APT)   » (APT) E: Unable to lock directory /var/lib/apt/lists/  
» (APT)   » (APT) E: Problem renaming the file /var/cache/apt/srcpkgcache.bin.J7Fixb to /var/cache/apt/srcpkgcache.bin - rename (2: No such file or directory)  
» (APT)   » (APT) W: You may want to run apt-get update to correct these problems  
» (APT)   » (APT) E: The package cache file is corrupted  

这是函数本身:

log_trace() {
local line
# Output automatically written to $_LOG_FILE
# Arguments: 1
# ARG -1: printf variable for formatting the log
while IFS= read -r line; do
__logger_core "trace" "$(printf "%s %s" "${1:-UNKNOWN}" "$line")"
done
}

我怎样才能做到这样呢?

» (APT) This is just a progress report, no error or warning
» (APT) You don't see STDERR output because it safely resides in the log file already
» (APT) All packages are up to date.

谢谢!

经过一些尝试和错误后,它的工作原理如下:

while read -r line; do
if [[ $line == "All packages are up to date." ]]; then
bool_update_required=0
fi
log_trace "(APT)" <<<"$line"
done < <(apt update 2>&1)       # format all `apt` output, incl. errors/warnings

换句话说,apt的输出,无论它是什么,都不会逃避我的格式化函数log_trace()

相关内容

  • 没有找到相关文章