How to add timestamp to STDERR redirection

后端 未结 13 2538
感情败类
感情败类 2020-11-28 05:10

In bash/ksh can we add timestamp to STDERR redirection?

E.g. myscript.sh 2> error.log

I want to get a timestamp written on the log too.

13条回答
  •  天涯浪人
    2020-11-28 05:29

    #!/bin/bash
    
    DEBUG=1
    
    LOG=$HOME/script_${0##*/}_$(date +%Y.%m.%d-%H.%M.%S-%N).log
    ERROR=$HOME/error.log
    
    exec 2> $ERROR
    exec 1> >(tee -ai $LOG)
    
    if [ $DEBUG = 0 ] ; then
        exec 4> >(xargs -i echo -e "[ debug ] {}")
    else
        exec 4> /dev/null
    fi
    
    # test
    echo " debug sth " >&4
    echo " log sth normal "
    type -f this_is_error
    echo " errot sth ..." >&2
    echo " finish ..." >&2>&4
    # close descriptor 4
    exec 4>&-
    

提交回复
热议问题