【问题标题】:How to prepend timestamp to the STDERR and redirect to a file如何将时间戳添加到 STDERR 并重定向到文件
【发布时间】:2014-08-01 09:51:31
【问题描述】:

我仅将 STDERR 重定向到文件(或多或少有效),但我还想为每个重定向添加/添加时间戳。我不想要每一行的时间,只是在块的开头。我试过这个:

UKMAC08:~ san$ ( date 1>&2; df -jj ) 2>&1 1>/dev/null  2>testErr.log; cat testErr.log 
Fri  1 Aug 2014 10:50:00 BST
df: illegal option -- j
usage: df [-b | -H | -h | -k | -m | -g | -P] [-ailn] [-T type] [-t] [filesystem ...]

这是在为不成功的运行做我想做的事情,但在成功时也会加上时间戳:

UKMAC08:~ san$ ( date 1>&2; df -h ) 2>&1 1>/dev/null  2>testErr.log; cat testErr.log 
Fri  1 Aug 2014 10:50:07 BST

我怎样才能避免这种情况。最好的!

【问题讨论】:

    标签: linux bash shell sh


    【解决方案1】:

    可以这样做:

    OUT=$(df -h 2>&1 >/dev/null) || { date; echo "$OUT"; } >testErr.log
    

    测试:

    $ : > testErr.log; OUT=$(df -jj 2>&1 >/dev/null) || { date -u; echo "$OUT"; } >testErr.log; cat testErr.log
    Fri Aug  1 12:10:29 UTC 2014
    df: invalid option -- 'j'
    Try 'df --help' for more information.
    $ : > testErr.log; OUT=$(df -h 2>&1 >/dev/null) || { date -u; echo "$OUT"; } >testErr.log; cat testErr.log
    (no output)
    

    您可以将>testErr.log 更改为>>testErr.log 以追加。

    这样会更有效率:

    OUT=$(exec df -h 2>&1 >/dev/null) || { date; echo "$OUT"; } >testErr.log
    

    【讨论】:

    • 我不希望时间戳在文件成功运行时出现在文件中,但是如您所见,您的代码正在这样做。这正是我要解决的问题。最好的!
    【解决方案2】:

    这样的事情怎么样:

    date > stderr.log
    command 2>> stderr.log
    

    这对我来说似乎是最简单的方法 - 只需在输出文件中预先设置日期,然后附加 stderr 输出,而不是覆盖文件...

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 1970-01-01
      • 2022-01-08
      • 2014-09-30
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      相关资源
      最近更新 更多