I have been working on a script that automatically checks on the state of 2 services that I require to be running 24/7 on a server that I manage.
The script works as I need, but I would really like to optimize it if possible. Specifically, I find that I want a way to reduce the need to type the command:
$(ps -ef | grep -v grep | grep zabbix_agentd | wc -l)
and
$(ps -ef | grep -v grep | grep zabbix_server | wc -l)
Any other feedback is greatly appreciated, I am new to bash scripting and trying to find the best way to get this to be as optimal as possible!
#!/bin/bash
zabbix_server="service zabbix-server"
zabbix_agent="service zabbix-agent"
logfile=/etc/scripts/zabbix/zabbix_auto_restart.log
zabbix_server_running=0
zabbix_agent_running=0
check_zabbix_agentd (){
if (( $(ps -ef | grep -v grep | grep zabbix_agentd | wc -l) <= 0 ))
then
$zabbix_agent start
echo `date` "$zabbix_agent was stopped... Restarting" >> $logfile
echo "************************************************" >> $logfile
#Send email to notify that the script ran
echo "$(date) $zabbix_agent was restarted from zabbix_restart.sh" | mutt -s "Zabbix Auto-restart Script Just Ran" <admin email address>
else
let zabbix_agent_running=1
fi
}
check_zabbix_server (){
if (( $(ps -ef | grep -v grep | grep zabbix_server | wc -l) <= 0 ))
then
$zabbix_server start
echo `date` "$zabbix_server was stopped... Restarting" >> $logfile
echo "************************************************" >> $logfile
#Send email to notify that the script ran
echo "$(date) $zabbix_server was restarted from zabbix_restart.sh" | mutt -s "Zabbix Auto-restart Script Just Ran" <admin email address>
else
let zabbix_server_running=1
fi
}
main_loop (){
until ((zabbix_server_running == 1 && zabbix_agent_running == 1));
do
check_zabbix_agentd
check_zabbix_server
sleep 1.5
done
}
main_loop