Crontab in practice
Edit your crontab, use absolute paths and understand the minimal environment cron runs in.
Each user has a personal table called a crontab. You never edit the file directly. Use the crontab command.
crontab -e # edit your crontab
crontab -l # list it
crontab -r # remove it (no confirmation!)Carefulcrontab -r deletes the whole table at once and the keys -e and -r sit next to each other. Keep a copy: crontab -l > crontab.bak.
Why a job works in the terminal but not in cron
Cron starts jobs with a very small environment: a short PATH, /bin/sh as the shell and no login files. Most failures come from that.
- Use absolute paths for commands and files:
/usr/bin/python3 /home/ana/report.py. - Set variables at the top of the crontab:
PATH=/usr/local/bin:/usr/bin:/bin. - Do not rely on
~/.bashrcor on the current directory. Usecd /path && commandwhen needed. - In a crontab,
%is special. Escape it as\%inside commands, for example indate +\%F.
System-wide jobs
The file /etc/crontab and the files in /etc/cron.d/ have an extra column with the user to run as. The folders /etc/cron.daily, /etc/cron.weekly and so on hold plain scripts.
# /etc/cron.d/backup
30 2 * * * root /usr/local/bin/backup.shTest yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.