`
#!/bin/bash
msg=$(find /home/testaccount/test.log -mmin -30 -exec grep test.service {} \; | tail -1)
test -n "$msg" &&
echo "$msg" |
mail -r '[email protected]' -s 'Database Aler' [email protected]
我上面有一个脚本,当有一个带有 test.service 的日志时,它会通过电子邮件发送给我,我已将其放入 cron 中,它将每 30 分钟运行一次,但我现在的问题是它总是每 30 分钟通过电子邮件发送相同的日志。
有没有办法给我发一次电子邮件,然后如果再次读取相同的日志,它就会停止向我发送电子邮件?
我需要阻止它每 30 分钟发送相同的日志,如果有带有 test.service 的新警报,它只会向我发送电子邮件。
要实现仅在有带有
test.service
的新日志条目时发送电子邮件的功能,您可以在单独的文件中跟踪上次处理的日志条目。这是执行此操作的脚本的更新版本:
#!/bin/bash
log_file="/home/testaccount/test.log"
last_handled_file="/path/to/last_handled.log"
# Read the last handled log entry timestamp from the file
if [ -f "$last_handled_file" ]; then
last_handled=$(cat "$last_handled_file")
else
last_handled=""
fi
# Get the most recent log entry with test.service within the last 30 minutes
msg=$(find "$log_file" -mmin -30 -exec grep test.service {} \; | tail -1)
# Check if there's a new log entry and it differs from the last handled one
if [ -n "$msg" ] && [ "$msg" != "$last_handled" ]; then
echo "$msg" |
mail -r '[email protected]' -s 'Database Alert' [email protected]
# Update the last handled log entry timestamp in the file
echo "$msg" > "$last_handled_file"
fi
在此版本中,我们引入了一个
last_handled_file
变量,它指向存储最后处理的日志条目的文件的路径。当脚本运行时,它会从此文件中读取最后处理的条目(如果存在)。处理新的日志条目后,它将与上次处理的条目进行比较,如果不同,则会发送一封电子邮件并使用新的日志条目更新 last_handled_file
。
确保将
/path/to/last_handled.log
替换为您要存储最后处理的日志条目的实际路径。
通过使用此方法,仅当有带有
test.service
的新日志条目时,脚本才会发送电子邮件,并且不会每 30 分钟通过电子邮件重复发送相同的日志条目。