簡體   English   中英

如何將 STDERR output 重定向到變量或 function 以便稍后附加到日志文件?

[英]How can I redirect STDERR output to a variable or function to be later appended to a log file?

這就是我嘗試僅將 STDERR outputapt重定向到日志文件的方式,同時使用兩次 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM