Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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_file="/etc/cron.d/restart_apache_crontab"
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..

share|improve this question
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
add comment

1 Answer

up vote 0 down vote accepted

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...

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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