Append text to stderr redirects in bash

前端 未结 4 1231
青春惊慌失措
青春惊慌失措 2020-12-08 17:09

Right now I\'m using exec to redirect stderr to an error log with

exec 2>> ${errorLog}

The only downside is that I have to start each

4条回答
  •  无人及你
    2020-12-08 17:46

    This example redirects stdout and stderr without loosing the original stdout and stderr. Also errors in the stdout handler are logged to the stderr handler. The file descriptors are saved in variables and closed in the child processes. Bash takes care, that no collisions occur.

    #! /bin/bash
    
    stamp ()
    {
      local LINE
      while IFS='' read -r LINE; do
        echo "$(date '+%Y-%m-%d %H:%M:%S,%N %z') $$ $LINE"
      done
    }
    
    exec {STDOUT}>&1
    exec {STDERR}>&2
    exec 2> >(exec {STDOUT}>&-; exec {STDERR}>&-; exec &>> stderr.log; stamp)
    exec > >(exec {STDOUT}>&-; exec {STDERR}>&-; exec >> stdout.log; stamp)
    
    for n in $(seq 3); do
      echo loop $n >&$STDOUT
      echo o$n
      echo e$n >&2
    done
    

    This requires a current Bash version but thanks to Shellshock one can rely on this nowadays.

提交回复
热议问题