![조건이 충족되는 경우에만 crontab 실행](https://linux55.com/image/61065/%EC%A1%B0%EA%B1%B4%EC%9D%B4%20%EC%B6%A9%EC%A1%B1%EB%90%98%EB%8A%94%20%EA%B2%BD%EC%9A%B0%EC%97%90%EB%A7%8C%20crontab%20%EC%8B%A4%ED%96%89.png)
웹 서버가 응답하지 않을 때마다 이메일을 보내는 bash 스크립트가 있는데, 이 스크립트는 cron
5분마다 실행됩니다. 하지만 사이트가 몇 시간 동안 다운되면 메시지가 한 개가 아닌 너무 많은 메시지를 받게 됩니다.
이메일을 한 번만 보내도록 하는 가장 좋은 방법은 무엇입니까? 이메일을 보내기 전에 환경 변수를 사용하여 확인해야 하나요? 웹 서버가 다시 시작되면 재설정해야 하나요? 환경을 오염시키지 않고 이를 수행할 수 있는 더 좋은 방법이 있습니까? 내가 지금 멍청한 짓을 하고 있는 걸까? 나는 쉘 스크립팅 기술에 자신이 없습니다.
#!/bin/sh
output=$(wget http://lon2315:8081 2>&1)
pattern="connected"
if [[ ! "$output" =~ "$pattern" ]]
then
echo "$output" | mail -s "Website is down" "[email protected]"
fi
답변1
환경 변수는 스크립트 "실행" 사이에 지속되지 않으므로 사용할 수 없다고 생각합니다.
또는 홈 디렉터리의 일부 임시 파일에 내용을 쓰고 /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" "[email protected]"
touch "$tempfile"
fi
else
[[ -f "$tempfile" ]] && rm "$tempfile"
fi
답변2
조금 더러워지긴 했지만, /tmp
서버를 다시 백업하면 삭제될 파일이나 그런 걸 어딘가에 넣어두겠습니다.
어쩌면 다음과 같은 것일 수도 있습니다.
#!/bin/sh
output=$(wget http://lon2315:8081 2>&1)
pattern="connected"
websitedownfile="/tmp/websitedown"
if [[ ! "$output" =~ "$pattern" ]]; then
if [[ -e $websitedownfile ]]; then
echo "$output" | mail -s "Website is down" "[email protected]"
fi
touch $websitedownfile
else
[[ -f $websitedownfile ]] && rm $websitedownfile
fi