I have a process I am running whereby I need to capture the logs from a daemon for the duration the process is running. I have a solution I've cobbled together, but I was hoping someone could point me at a slightly more elegant way to do it. The specific thing that's irking me is that, because I'm using set -e
to alert me to any problems, kill
generates an error from tail
which I have to eat with || :
, which to me is an ugly hack.
我正在运行一个进程,在此过程中,我需要从一个守护进程中捕获进程运行期间的日志。我拼凑出了一个解决方案,但我希望有人能给我一个更优雅的方法。让我厌烦的是,因为我用集合e来提醒我任何问题,kill会产生一个错误,我必须用||吃这个,这对我来说是一个丑陋的技巧。
#!/bin/bash
set -e
LOGDIR="/path/to/logs"
LOCKFILE="/path/to/lockfile"
NOW=$( date +'%Y-%m-%d-%H%M' )
bail() {
echo "$(hostname) $(pwd) error in line $1 of THING" | mail -s "Error: THING on $(hostname) line# $1" me@example.com
}
if [ -f $LOCKFILE ] ; then
echo "$(hostname) $(pwd) ${0} is locked $(ls -l ${LOCKFILE})"| mail -s "LOCKED: THING" me@example.com
exit
else
trap "rm -f $LOCKFILE" EXIT
trap 'bail $LINENO' ERR
fi
echo $$ > $LOCKFILE
/bin/date >> $LOCKFILE
tail -f path/to/daemon/logfile > $LOGDIR/${NOW}-THING.log &
TAILPID=$!
sleep 1
/path/to/monitored-process
sleep 1 # Allow for last couple log entries to flush
kill $TAILPID
wait $TAILPID || : # Need the no-op to eat the expected error from `kill`ing tail
/bin/rm -f $LOCKFILE
1 个解决方案
#1
2
In my opinion, what you have is quite elegant.
在我看来,你所拥有的是相当高雅的。
As a solution, how about putting set +e
just before the kill, and set -e
after? Since you are expecting the error status when tail is killed, don't look for it.
作为一种解决方案,不如在杀之前加上集合+e,然后再加上-e ?由于您期望在结束尾部时出现错误状态,所以不要查找它。
#1
2
In my opinion, what you have is quite elegant.
在我看来,你所拥有的是相当高雅的。
As a solution, how about putting set +e
just before the kill, and set -e
after? Since you are expecting the error status when tail is killed, don't look for it.
作为一种解决方案,不如在杀之前加上集合+e,然后再加上-e ?由于您期望在结束尾部时出现错误状态,所以不要查找它。