[英]How can I redirect STDERR output to a variable or function to be later appended to a log file?
这就是我尝试仅将 STDERR output从apt
重定向到日志文件的方式,同时使用两次 function log_trace()
在终端上可以看到apt
进度报告:
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
问题是因为每个 output 行在循环中处理了两次,我从log_trace()
(实际上来自另一个 function __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
这是 function 本身:
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
output,无论它是什么,都不会逃脱我的格式 function log_trace()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.