I have this bash script whose job is to monitor a log file for the occurrence of a certain line. When located, the script will send out an email warning an开发者_StackOverflow中文版d then terminate itself. For some reason, it keeps on running. How can I be sure to terminate bash script below:
#!/bin/sh
tail -n 0 -f output.err | grep --line-buffered "Exception" | while read line
do
echo "An exception has been detected!" | mail -s "ALERT" monitor@company.com
exit 0
done
You are opening a subshell in the while read
and that subshell is who is exiting, not the proper one.
Try before entering the while loop:
SHELLPID=$$
And then in the loop:
kill $SHELLPID
exit 0
Or change your loop to not use a subshell.
Since the parent script is always going to be in the tail -f
which never ends I think you have no other choice than killing it from the inner subshell.
Try something like this:
tail -n 0 -f output.err | grep --line-buffered "Exception" | while read line do echo "An exception has been detected!" | mail -s "ALERT" monitor@company.com kill -term `ps ax | grep tail | grep output.err | awk '{print $1}'` done
This should work, provided you have only one tail keeping an eye on this particular file.
精彩评论