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

来源:互联网 发布:超星阅读器windows 编辑:程序博客网 时间:2024/06/07 04:44

示例

#! /bin/bashexec 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/bashecho "The content of my_file.txt is: $(<my_file.txt)"

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

0 0
原创粉丝点击