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

标签 linux bash shell sh

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

相关文章:

linux - 将文件解压缩到特定的日期文件夹

linux - 全局环境的来源

bash 扫描数百万个文件并快速扫描一个值

linux - 解析日志文件的shell脚本

linux - ls 命令的前两个结果

c++ - 如何对进程的 'manager' 和 'worker' 线程进行优先级排序(或设置调度策略)?

linux - 内核空间内存布局

linux - 递归地在子文件夹中添加新文件

c - Shell 脚本 -(编译 C)

linux - 将行插入多个指定文件