Crontab not working | Linux
Cron passes a minimal set of environment variables to your jobs. To see the difference, add a dummy job like this:
* * * * * env > /tmp/env.output
Wait for /tmp/env.output to be created, then remove the job again. Now compare the contents of /tmp/env.output with the output of env run in your regular terminal.
A common “gotcha” here is the PATH environment variable being different. Maybe your cron script uses the command somecommand found in /opt/someApp/bin, which you’ve added to PATH in /etc/environment? cron does not read that file, so runnning somecommand from your script will fail when run with cron, but work when run in a terminal.
To get around that, just set your own PATH variable at the top of the script. E.g.
#!/bin/bash
PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# rest of script follows
Some prefer to just use absolute paths to all the commands instead. I recommend against that. Consider what happens if you want to run your script on a different system, and on that system, the command is in /opt/someAppv2.2/bin instead. You’d have to go through the whole script replacing /opt/someApp/bin with /opt/someAppv2.2/bin instead of just doing a small edit on the first line of the script.
You can also set the PATH variable in the crontab file, which will apply to all cron jobs. E.g.
PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
15 1 * * * backupscript –incremental /home /root
- If you forget to add a newline at the end of the crontab file. In other words, the crontab file should end with an empty line.
Below is the relevant section in the man pages for this issue (man crontab then skip to the end):
Although cron requires that each entry in a crontab end in a newline character, neither the crontab command nor the cron daemon will detect this error. Instead, the crontab will appear to load normally. However, the command will never run. The best choice is to ensure that your crontab has a blank line at the end.
- Crontab service not running:
Run “pgrep cron”
If you see no number, then cron is not running. sudo /etc/init.d/cron start can be used to start cron.
Or run “sudo service cron start” to start the service
- File permissions
Check that the script is given proper execute permissions and the user running the cronjob is having the permissions to execute and write.
chmod 0755 myscript.sh
In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.