0

I know how to execute multiple command in one crontab line but I can't understand why my last command is not being executed. My (root) crontab is like

5 0 1,15 * * echo $(date) >> /root/certbot_cronjob_log.txt && /usr/services/certbot/certbot-auto renew --text >>/root/certbot_cronjob_log.txt 2>&1 && service nginx restart

What I want to achieve: Write the current date to file certbot_cronjob_log.txt, then run the autorenew script "certbot-auto", write it's output into the file and then restart nginx.

It does everything until the point "restart nginx". When I run exactly this whole command in my terminal (as root) it is working and nginx restarts.

I already tried this:

5 0 1,15 * * bash -c 'echo $(date) >> /root/certbot_cronjob_log.txt && /usr/services/certbot/certbot-auto renew --text >>/root/certbot_cronjob_log.txt 2>&1 && service nginx restart' 

Any ideas?

  • 1
    Create a bash script and run that via cron instead - that will probably have better results.. – Thomas Ward Jul 14 '17 at 11:18
  • 1
    Probably because /usr/sbin (where the service command lives) isn't in the crontab path - same likely applies to /sbin/restart. (Even if you move your commands to a separate script you will need to address this, either by using full paths to the executables or by defining a suitable PATH) – steeldriver Jul 14 '17 at 12:11
  • Thank you @steeldriver. /usr/sbin/service nginx restart did the trick! – Lumpy Jul 14 '17 at 13:07
2

The /usr/sbin directory (where the upstart service command lives) isn't in the default crontab path, so you will either need to add an explicit PATH assignment in the top of your crontab file e.g.:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

or use the full path in your command

/usr/sbin/service nginx restart

You will need to do this whether you keep it as an in-line command or break it out into a shell script (although you'd then have the choice of setting the PATH in the script versus in the crontab file).


FWIW since variants of this question are frequently asked, here's the default cron environment on my 16.04 system, obtained by running /usr/bin/printenv > /tmp/cronenv from root's crontab:

LANGUAGE=en_CA:en
HOME=/root
LOGNAME=root
PATH=/usr/bin:/bin
LANG=en_CA.UTF-8
SHELL=/bin/sh
PWD=/root

Note how minimal it is - this is often why commands or scripts that run fine in an interactive shell fail when run from cron.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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