我只将 STDERR 重定向到一个文件(或多或少可以正常工作),但我还想为每次重定向添加/添加时间戳。我不想要每一行的时间,只是在 block 的开头。我试过这个:
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
我怎样才能避免这种情况。最好!
最佳答案
这可以做到:
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
关于linux - 如何将时间戳添加到 STDERR 并重定向到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25077465/