如何将时间戳添加到STDERR并重定向到文件

时间:2014-08-01 09:51:31

标签: linux bash shell sh

我只将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

我该如何避免这种情况。最好!

2 个答案:

答案 0 :(得分:2)

这可以做到:

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

答案 1 :(得分:0)

这样的事情怎么样:

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

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