【发布时间】:2014-07-14 13:16:22
【问题描述】:
我希望在我的 shell 脚本中执行的命令的所有错误都写在一个日志文件中,这样执行起来很简单
exec 2>> /var/log/mylog.txt
但如果我想在每行添加错误前的日期怎么办?
【问题讨论】:
我希望在我的 shell 脚本中执行的命令的所有错误都写在一个日志文件中,这样执行起来很简单
exec 2>> /var/log/mylog.txt
但如果我想在每行添加错误前的日期怎么办?
【问题讨论】:
如果您使用的是bash,您可以访问可能达到此目的的协同流程:
#!/bin/bash
# The co-process responsible to add the date
coproc myproc {
( bash -c 'while read line; do echo $(date): ${line}; done' 3>&1 1>&2- 2>&3- )
}
# Redirect stderr to the co-process
exec 2>&${myproc[1]}
# Here my script -- classical; no (visible) redirection
ls non-existant-file1 existant-file non-existant-file2
将以上内容另存为t.sh:
sh$ touch existant-file
sh$ ./t.sh 2> error.log
existant-file
sh$ cat error.log
Tue Jul 15 00:15:29 CEST 2014: ls: cannot access non-existant-file1: No such file or directory
Tue Jul 15 00:15:29 CEST 2014: ls: cannot access non-existant-file2: No such file or directory
【讨论】:
想到的第一个选项是使用先进先出,以及一些重定向:
我保留这个答案,因为它可能就足够了;但其他选项可用 - 请参阅我的其他答案
#!/bin/sh
TEMPDIR=`mktemp -d`
mkfifo "${TEMPDIR}/fifo"
(awk '{"date" | getline the_date; print the_date ": " $0; fflush() }' < "${TEMPDIR}/fifo" ) &
exec 2> "${TEMPDIR}/fifo"
rm -f "${TEMPDIR}/fifo"
#
# Your commands here
#
exec 2>&-
【讨论】:
创建一个管道并通过 perl 脚本运行您的 stderr。比如:
#!/bin/sh
trap 'rm -f $F' 0
F=$(mktemp)
rm $F
mkfifo $F
perl -ne 'print localtime() . ": " . $_' < $F >&2 &
exec 2> $F
正如所写,这会将时间戳和消息打印到与脚本开始时相同的 stderr,因此您可以通过在脚本运行时重定向来附加到日志文件。或者,您可以在调用 perl 的行上硬编码重定向。
【讨论】: