shell script:
#!/bin/sh
services=( httpd named proftpd mysqld dovecot postfix webmin)
for service in ${services[@]}
do
if ps ax | grep -v grep | grep $service > /dev/null
then
echo "$service service running, everything is fine"
else
echo "$service is not running"
service $service start
fi
done
file executable, running from root user
command:
bash /etc/mycron/checkServices.sh
tried sh and just /etc/myc开发者_Python百科ron/checkServices.sh
doesn't run
#!/bin/sh
services=( httpd named proftpd mysqld dovecot postfix webmin)
for service in ${services[@]}; do
if ps ax | grep -v grep | grep $service > /dev/null; then
echo "$service service running, everything is fine";
else
echo "$service is not running";
service $service start;
fi;
done;
Works fine here... maybe you want to add after #!/bin/sh
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/opt/usr/bin:/opt/usr/sbin:/usr/local/bin:/usr/local/sbin"
You could also do chmod 775 /etc/mycron/checkServices.sh
to make it executable, which is needed for cron. Then you would also not need to call bash /etc/mycron/checkServices.sh
and can just call /etc/mycron/checkServices.sh
the #!/bin/sh
tells the executable loader to load the file with /bin/sh
if you invoke bash /etc/mycron/checkServices.sh
you will start bash which on his turn would start /bin/sh
to finally execute your script.
Since the for loop in bash / sh uses the IFS variable ($IFS
) as delimiter, you could also make the line services=(httpd named proftpd mysqld dovecot postfix webmin)
as services="httpd named proftpd mysqld dovecot postfix webmin"
since this is more general
Just as a general diagnostic process, it's sensible to insert trace statements into the script such as:
- echo "Starting..."
- echo "Checking for running service '$service'..."
- which/whereis service
- echo "Service has been started."
- temporarily remove the
> /dev/null
forps
.
Then execute under cron with stdout and stderr redirected to a log file.
That allows you to identify the exact line that's failing. As others have said, it looks likely to be the "service" or "$service" commands aren't found because the PATH isn't set to include them. You do realise "service" itself is being sought as an external command that presumably launched $service in turn? Also keep an eye on root's mail, as cron sometimes sends error reports via mail.
精彩评论