How To's

How to Use Scripts in Crontab

3,159 views · 1 found this helpful

Was this helpful?

Problem

Adding bash scripts to crontab

tl;dr

Use full path to the script and inside crontab itself. For example, /root/script.sh instead of ~/script.sh, and /etc/init.d/abc restart instead of service abc restart. Bash does not recognize shortcuts such as ~ when called outside the shell.

Solution

Bash scripts require you to use a full path to any tools or services you intend to use. Something like

#!/bin/bash
service httpd restart

Will work fine if you try to run it manually. However, it will fail to execute if you try to run it via cron, or call this script from a different script.

As such, use commands such as /etc/init.d/service action, and /etc/bin/bash or /usr/bin/test instead of simply bash or test.

Sample allowed script

#!/bin/bash
#Restarts Apache if it's not running
/etc/init.d/httpd restart

Note the full path to httpd instead of service httpd restart - the latter will not work with crontab>

Sample cronjob

crontab -e

0 0 * * * /root/scripts/restartapache.sh

This will run the restartapache.sh script located in ~/scripts/ every day at 0:00 (midnight).

  • Updated

← All articles

Still stuck?

Our engineers answer tickets directly, 24/7.