I'm trying to learn Bash scripting and for fun I would like to write a script which will monitor the httpd.service
.
The basic construct looks like this:
#!/bin/bash
SERVICE=httpd.service
if [ "systemctl show -p ActiveState $SERVICE | sed 's/ActiveState=//g'" != "active" ] && [ "systemctl show -p SubState $SERVICE | sed 's/SubState=//g'" != "running" ]
then
echo "$SERVICE is inactive" | mailx -r [email protected] -s "$SERVICE not running on $HOSTNAME" [email protected]
fi
it works. Whether is written in a secure and best practice way, I guess not but its my second day and I first need to get an idea behind scripting in generall.
How can I get the result of the two test
conditions in a variable so that I could print the status and substatus in to the mail ? I guess I could do something like:
#!/bin/bash
SERVICE=httpd.service
STATE=$(systemctl show -p ActiveState $SERVICE | sed 's/ActiveState=//g')
SUBSTATE=$(systemctl show -p SubState $SERVICE | sed 's/SubState=//g')
if [ "$STATE" != "active" ] && [ "SUBSTATE" != "running" ]
then
echo "$SERVICE state is $STATE and substate is $SUBSTATE"
fi
But not sure if this is a elegant way to do this ?
EDIT
Thanks for all your valuable comments! I've up voted all of them!
So, basically I ended up doing it in the following way:
#!/bin/bash
SERVICE=httpd.service
HOST=$(grep '^ServerName' /etc/httpd/conf/httpd.conf | sed 's/^.* //')
[email protected]
if [ "$(systemctl show -p ActiveState $SERVICE | sed 's/ActiveState=//g')" = "active" ]
then
echo "$SERVICE is running" >/dev/null
else
systemctl restart $SERVICE 2>/dev/null
if [ "$(systemctl show -p ActiveState $SERVICE | sed 's/ActiveState=//g')" = "active" ]
then
echo "$SERVICE on $HOST has been started" | mailx -r "${HOST}"@blabla.com -s "$SERVICE on $HOST restarted" $EMAIL
else
echo "$SERVICE on $HOST is stopped and could not be started!" | mailx -r "${HOST}"@blabla.com -s "$SERVICE on $HOST has encountered a problem!" $EMAIL
fi
fi
Could you please have a look at it? Are there any style, not POSIX compliant things used ?
if [ "$(cmd)" ...
, with the quotes. – ilkkachu Sep 5 '18 at 9:26systemctl show --value -p ActiveState
to avoid having to usesed
. – Stéphane Chazelas Sep 5 '18 at 20:40