How to add timestamp to STDERR redirection

后端 未结 13 2474
感情败类
感情败类 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:30

    Redirections are taken in order. Try this:

    Given a script -

    $: cat tst
    echo a
    sleep 2
    echo 1 >&2
    echo b
    sleep 2
    echo 2 >&2
    echo c
    sleep 2
    echo 3 >&2
    echo d
    

    I get the following

    $: ./tst 2>&1 1>stdout | sed 's/^/echo $(date +%Y%m%dT%H%M%S) /; e'
    20180925T084008 1
    20180925T084010 2
    20180925T084012 3
    

    And as much as I dislike awk, it does avoid the redundant subcalls to date.

    $: ./tst 2>&1 1>stdout | awk "{ print strftime(\"%Y%m%dT%H%M%S \") \$0; fflush() }"; >stderr
    
    $: cat stderr
    20180925T084414 1
    20180925T084416 2
    20180925T084418 3
    
    $: cat stdout
    a
    b
    c
    d
    

提交回复
热议问题