Shell script not executing from cron job

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 

executable file executed as root

Command:

 bash /etc/mycron/checkServices.sh 

tried sh and just /etc/mycron/checkServices.sh

does not start

0
source share
2 answers
 #!/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 well 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 can also make chmod 775 /etc/mycron/checkServices.sh to make it executable, which is necessary for cron. Then you will also not need to call bash /etc/mycron/checkServices.sh and can just call /etc/mycron/checkServices.sh #!/bin/sh tells the executable to load the file using /bin/sh if you call bash /etc/mycron/checkServices.sh , you run bash, which in turn starts /bin/sh to finally execute your script.

Since the for loop in bash / sh uses the IFS variable ( $IFS ) as a delimiter, you can 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

+5
source

As a normal diagnostic process, it is wise to embed trace instructions in a script, for example:

  • echo "Starting ..."
  • echo "Testing the service $ service" ... "
  • service / whereis
  • echo "The service has been started."
  • temporarily remove > /dev/null for ps .

Then execute in cron with stdout and stderr redirected to the log file.

This allows you to identify the exact string that is not working. As others have said, it seems that the "service" or "$ service" commands were not found because PATH is not set to enable them. Do you understand that the "service" itself is requested as an external command that supposedly starts $ service in turn? Also keep an eye on root mail, as cron sometimes sends bug reports by mail.

+1
source

All Articles