Home > Back-end >  How can I redirect STDERR output to a variable or function to be later appended to a log file?
How can I redirect STDERR output to a variable or function to be later appended to a log file?

Time:01-10

This is how I'm trying to redirect only the STDERR output from apt to a log file, while the apt progress report is visible on the terminal using function log_trace() twice:

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

The problem is since each output line is processed in the loop twice, I get custom line prefix » (APT) from log_trace() (actually from another function __logger_core) printed twice as well:

  » (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  

And this is the function itself:

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
}

How can I achieve something like this:

  » (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.

Thank you!

CodePudding user response:

After some trial and error, this works as follows:

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

In other words, apt output, whatever it is, doesn't escape my formatting function log_trace().

  • Related