Shell中, 为标准错误输出添加时间戳

示例

#! /bin/bash
exec 2> >(while read line; do echo "[$(date "+%Y-%m-%d %H:%M:%S")] $line"; done)
ls /not/exist/path

运行

chmod u+x stderr_ts.sh
./stderr_ts.sh

输出

[2017-03-15 18:33:33] ls: /not/exist/path: No such file or directory

原理

1. 使用exec将当前Shell的标准错误输出(STDERR)重定向

exec的完整用法如下:

exec
    exec [-cl] [-a name] [command [arguments]]

根据这里的解释:

If command is supplied, it replaces the shell without creating a new process. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what the login program does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to command. If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed.
If no command is specified, redirections may be used to affect the current shell environment. If there are no redirection errors, the return status is zero; otherwise the return status is non-zero.
1. 当command参数存在时, exec会用command覆盖当前Shell,即在command执行完成后,不再继续执行当前Shell脚本。
2. 当command参数不存在时, exec可以重定向当前的Shell环境。

2. 使用进程替代(Process Substitution)读取标准错误输出(STDERR)

进程替代(Process Substitution)2种形式
1. <(list): 将进程列表(process list)的输出写到外部文件
2. >(list): 将外部文件作为进程列表(process list)的输入

另外

有一种Shell语法跟进程替代(Process Substitution)很类似,看起来是这样子的: $(< file)
举个例子:

#! /bin/bash
echo "The content of my_file.txt is: $(<my_file.txt)"

这种用法叫command substitution,它的常见形式是$(command)或者`command `,而这种写法$(< file)$(cat file)功能相同,但是读取速度更快。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值