appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Crontab in practice

Lesson 2 of 59 minBeginner

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 ~/.bashrc or on the current directory. Use cd /path && command when needed.
  • In a crontab, % is special. Escape it as \% inside commands, for example in date +\%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.sh

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Why use absolute paths in a crontab?
2. What does crontab -r do?
HintThe flag is a lowercase L.

Key terms