我有一个 bash 脚本,每当 Web 服务器没有响应时,它就会给我发电子邮件,并且脚本cron每 5 分钟运行一次。但是,如果网站关闭几个小时,我会收到太多消息,而不仅仅是一条消息。
让它只发送一次电子邮件的最佳方法是什么?我应该使用环境变量并在发送电子邮件/在 Web 服务器再次启动时重置它之前检查它吗?有没有更好的方法来做到这一点(不污染环境)?我现在在做什么傻事吗?我对自己的 shell 脚本技能没有信心。
#!/bin/sh
output=$(wget http://lon2315:8081 2>&1)
pattern="connected"
if [[ ! "$output" =~ "$pattern" ]]
then
echo "$output" | mail -s "Website is down" "myemail@asdf.com"
fi
Run Code Online (Sandbox Code Playgroud)
我认为您不能使用环境变量,因为它们不会在脚本“运行”之间持续存在。
或者,您可以写入/tmp主目录中或某处的临时文件,然后每次都检查它?
例如,像
#!/bin/sh
output=$(wget http://lon2315:8081 2>&1)
pattern="connected"
tempfile='/tmp/my_website_is_down'
if [[ ! "$output" =~ "$pattern" ]]
then
if ! [[ -f "$tempfile" ]]; then
echo "$output" | mail -s "Website is down" "myemail@asdf.com"
touch "$tempfile"
fi
else
[[ -f "$tempfile" ]] && rm "$tempfile"
fi
Run Code Online (Sandbox Code Playgroud)