I am creating this cron as apache user and want to run this cron as root, below is my code snippet:

# Create a cron job to restart apache
cron_job="*/1 * * * * root condrestart-apache.sh"
echo "$cron_job" > $cron_file
chmod 777 $cron_file
exit 0

Provided sufficient privileges to cron.d directory (changes directory group to apache user) and script generated a cron file restart_apache_crontab at /etc/cron.d/ using the above script

condrestart-apache.sh contains below code and has sufficient access permissions for apache user:

rm -f /etc/cron.d/restart_apache_crontab
/sbin/service httpd restart > restart-apache.log

This will first remove cron and then restart apache (means cron will run only for 1 time)

I am able to create cron as apache user but not able to execute it as root user.

Please help me on this.. code snippet will be really helpful..

  • 1
    Why not just run the cronjob as root ? Do you not have access to run as root ? – Lawrence Dec 2 '13 at 12:12

In the cronjob "*/1 * * * * root condrestart-apache.sh" I would expect an absolute path to your restart script e.g. /usr/local/sbin/condrestart-apache.sh.

And condrestart-apache.sh must be an executable (e.g. chmod 755) shell script and of course include something like #!/bin/sh which is missing from your snippet.

The primary reason to restart Apache would be to effect a configuration change, so checking if the syntax is correct before trying to restart your webserver and killing it may be a good idea as well...

# /usr/local/sbin/condrestart-apache.sh
rm -f /etc/cron.d/restart_apache_crontab
/usr/sbin/apachectl configtest
if [ $RETVAL -ne  0 ]; then
   echo "Configuration file invalid"
   exit 1
/sbin/service httpd restart 
if [ $RETVAL -ne  0 ]; then
   echo "Restart Failed"
   exit 1
  • Thanks @HBruijn, you saved my day.. nice snippet.. worked for me.. – Viren H. Ajmera Dec 3 '13 at 6:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.