Cron Jobs Explained. Crontab Syntax, Debugging, Locking and Docker
Cron is the Linux scheduler that runs commands at set times. It is simple, but does have its tricks. This guide gives you copy-paste examples to get you started.
Index
- Cron syntax: every 15 minutes and weekdays at 9 AM
- Works in terminal, fails in cron
- Basic setup: editor, logs, permissions
- Stop overlapping cronjob runs with flock
- Last day of the month and first Thursday
1. Cron syntax: every 15 minutes and weekdays at 9 AM
A crontab line has 5 time fields, then the command:
┌───────── minute (0-59)
│ ┌─────── hour (0-23)
│ │ ┌───── day of month (1-31)
│ │ │ ┌─── month (1-12)
│ │ │ │ ┌─ day of week (0-7, 0 and 7 = Sunday)
│ │ │ │ │
* * * * * command-to-run
Special characters:
| Char | Meaning | Example |
|---|---|---|
* |
every value | * = every minute |
*/n |
every n-th value | */15 = every 15 min |
a-b |
range | 1-5 = Mon to Fri |
a,b |
list | 1,15 = the 1st and 15th |
Example 1: run a script every 15 minutes
*/15 * * * * /home/dev/scripts/sync.sh
Runs at :00, :15, :30 and :45 of every hour.
Example 2: run a script on weekdays at 9 AM
0 9 * * 1-5 /home/dev/scripts/report.sh
Minute 0, hour 9, any day or month, Monday (1) to Friday (5).
Try it in 2 minutes
Add this with crontab -e:
* * * * * date >> /tmp/cron-test.log
Wait two minutes, then check:
cat /tmp/cron-test.log
You should see one timestamp per minute.
Tip: cron uses the server’s timezone. Check it with
date. In containers it is usually UTC. To sanity-check an expression, paste it into crontab.guru.
2. Works in terminal, fails in cron
Usual way to develop a chron job is to run a test a command in a terminal and paste it in the crontab. The cronjob may fail:
Why: cron runs jobs in a minimal environment, not your login shell.
| Your terminal | Cron |
|---|---|
Full $PATH from .bashrc / .profile |
PATH=/usr/bin:/bin only |
| Your exported variables | None of them |
| Current directory = where you are | Working directory depends on the cron implementation |
Uses bash |
Uses /bin/sh by default |
Reproducible failing example
Step 1. Add to ~/.bashrc:
export PATH="$HOME/bin:$PATH"
export APP_ENV="production"
Step 2. Create a custom tool, a script, and a data file:
mkdir -p ~/bin ~/data
printf '#!/bin/bash\necho "hello-tool ran"\n' > ~/bin/hello-tool
chmod +x ~/bin/hello-tool
echo "some input" > ~/data/input.txt
Step 3. Create ~/report.sh:
#!/bin/bash
hello-tool
echo "APP_ENV=$APP_ENV"
cat data/input.txt
chmod +x ~/report.sh
Run it from ~ in your terminal:
hello-tool ran
APP_ENV=production
some input
Step 4. Schedule it, replacing dev with your username:
* * * * * /home/dev/report.sh >> /home/dev/report.log 2>&1
Step 5. Check the log after a minute (cat ~/report.log). Example output:
/home/dev/report.sh: line 2: hello-tool: command not found
APP_ENV=
cat: data/input.txt: No such file or directory
(This is typical output. Exact wording varies slightly by distro.)
What went wrong
| Log line | Cause |
|---|---|
hello-tool: command not found |
~/bin was added to PATH in .bashrc, which cron never reads |
APP_ENV= (empty) |
variable exported in .bashrc, not visible to cron |
data/input.txt: No such file |
relative path; cron’s working directory is not where you tested |
The fix
Make the script self-contained (~/report.sh). Important is to include env variables (on top).
#!/bin/bash
export PATH="$HOME/bin:/usr/local/bin:/usr/bin:/bin"
export APP_ENV="production"
cd "$(dirname "$0")" || exit 1 # run from the script's own folder
hello-tool
echo "APP_ENV=$APP_ENV"
cat data/input.txt
Or set variables at the top of the crontab (they apply to all jobs below):
PATH=/home/dev/bin:/usr/local/bin:/usr/bin:/bin
APP_ENV=production
* * * * * cd /home/dev && /home/dev/report.sh >> /home/dev/report.log 2>&1
Debugging trick: see cron’s real environment
* * * * * env > /tmp/cron-env.txt
Then compare:
diff <(sort /tmp/cron-env.txt) <(env | sort)
Checklist: use absolute paths, set PATH explicitly, never rely on .bashrc, and always redirect output with >> file 2>&1.
3. Basic setup: editor, logs and permissions
Edit your crontab
crontab -e # edit
crontab -l # list
crontab -r # remove ALL (no confirmation!)
Before testing an entry, make sure cron is running:
# Debian / Ubuntu
sudo systemctl enable --now cron
systemctl status cron
# RHEL / Rocky / Fedora
sudo systemctl enable --now crond
systemctl status crond
After saving, confirm the entry with crontab -l. crontab -r removes only the current user’s crontab and asks for no confirmation, so use it carefully.
If a crontab is saved with invalid syntax, the cron daemon will usually ignore it rather than running only the valid-looking entries. Remove or fix the invalid line, then confirm the complete file again with crontab -l.
How to exit the editor
| Editor | Save and quit | Quit without saving |
|---|---|---|
| vim | Esc, then :wq, Enter |
Esc, then :q!, Enter |
| nano | Ctrl+O, Enter, then Ctrl+X |
Ctrl+X, then N |
Prefer nano? Pick it for one session:
EDITOR=nano crontab -e
Or run select-editor on Debian/Ubuntu to set it permanently.
Where do the logs of cronjob go?
Cron logs that a job started. It does not log the job’s own output.
# Debian / Ubuntu
grep CRON /var/log/syslog
journalctl -u cron
# RHEL / Rocky / Fedora
sudo tail /var/log/cron
journalctl -u crond
Sample line:
Nov 19 09:00:01 server CRON[1234]: (dev) CMD (/home/dev/scripts/report.sh)
For the script’s own output, redirect it yourself to display logs in a file:
0 9 * * 1-5 /home/dev/scripts/report.sh >> /home/dev/report.log 2>&1
the
>>will always overwrite the contnet of the file. if you like to concatenate use single>.
Permissions
chmod +x /home/dev/scripts/report.sh
ls -l /home/dev/scripts/report.sh # look for the "x" bits
Output:
drwxr-xr-x@ 3 ubuntu staff 96 14 Nov 21:54 report.sh
Also check:
- The script has a shebang on line 1:
#!/bin/bash - The user running the job can write to the log file’s folder
- For beginner examples, prefer a log inside the user’s home directory, such as
/home/dev/report.log
4. Stop overlapping cronjob runs with flock
Flock is able to manipulate locks on files and thus allowing/preventing the run of a job. Locks are used as a semaphor to signal when job can run.
Comon problem: a job runs every minute but sometimes takes longer to finish. Cron starts the script and they pile up.
Solution: flock takes a lock file. If the lock is held, the new run exits immediately.
Lock the file for the duration of the run:
* * * * * flock -n /tmp/slow-job.lock /home/dev/scripts/slow.sh >> /home/dev/slow.log 2>&1
-n= don’t wait; exit at once if the lock is taken- The lock is released automatically when the process ends, even after a crash (unlike PID files)
Try it
Create ~/scripts/slow.sh:
#!/bin/bash
echo "$(date +%T) start"
sleep 90
echo "$(date +%T) done"
chmod +x ~/scripts/slow.sh
How install the cronjob mentioned above using crontab -e.
Without flock, cat /home/dev/slow.log shows overlapping starts:
10:00:01 start
10:01:01 start <- second copy while the first is still running
10:01:31 done
10:02:01 start
10:02:31 done
With flock, the minute-1 run is skipped because the lock is still held:
10:00:01 start
10:01:31 done
10:02:01 start
10:03:31 done
Test the lock by hand (no cron needed)
# Terminal 1
flock -n /tmp/demo.lock sleep 30
# Terminal 2, while terminal 1 is running
flock -n /tmp/demo.lock echo "got lock"; echo "exit code: $?"
# -> exit code: 1 (lock busy, command did not run)
Comand variants:
flock -w 10 /tmp/job.lock ./job.sh # wait up to 10s, then give up
flock -n -E 0 /tmp/job.lock ./job.sh # exit 0 (not 1) when skipped, quiet for monitoring
flockis part ofutil-linux(preinstalled on most Linux distros). On macOS it is not available by default, use brew.
5. Complex cronjob schedules: last day of the month, first Thursday
Standard 5-field cron cannot express these. The simple, practical fix: schedule a broader window, then check the date in the command.
Two things to know first
1. % must be escaped as \% in crontab, because cron treats a bare % as a newline.
2. The day-of-month / day-of-week “OR” problem. If you restrict both fields, cron runs when either matches:
# Looks like "first Thursday", but runs on every day 1-7
# OR every Thursday
0 9 1-7 * 4 /path/job.sh
Last day of the month
Run on days 28-31, then proceed only if tomorrow is the 1st:
0 23 28-31 * * [ "$(date -d tomorrow +\%d)" = "01" ] && /home/dev/scripts/month-end.sh
Test the check in your terminal:
# Linux (GNU date)
date -d tomorrow +%d
# macOS / BSD
date -v+1d +%d
First Thursday of the month
Run every Thursday, then proceed only if the day is 1-7:
0 9 * * 4 [ "$(date +\%d)" -le 7 ] && /home/dev/scripts/first-thursday.sh
Test the check:
[ "$(date +%d)" -le 7 ] && echo "first week" || echo "not first week"
Last Friday of the month (bonus)
Run every Friday, proceed only if the next Friday is in a different month:
0 9 * * 5 [ "$(date -d '+7 days' +\%m)" != "$(date +\%m)" ] && /home/dev/scripts/last-friday.sh
Cleaner option: move the check into the script
Crontab lines get ugly. Keep the schedule simple and put the guard first in the script:
#!/bin/bash
# month-end.sh: only run on the last day of the month
[ "$(date -d tomorrow +%d)" = "01" ] || exit 0
echo "Running month-end job"
On macOS/BSD, change the guard to:
[ "$(date -v+1d +%d)" = "01" ] || exit 0
0 23 28-31 * * /home/dev/scripts/month-end.sh
Limits of this approach
date -dis GNU date (Linux). macOS/BSD usedate -v+1d.
Alternative: systemd timers
If you need a clean expression, systemd supports it natively:
# first Thursday at 09:00
OnCalendar=Thu *-*-01..07 09:00
# last day of the month at 23:00
OnCalendar=*-*-~01 23:00
Cheat sheet
*/15 * * * * every 15 minutes
0 9 * * 1-5 weekdays at 9:00
0 0 1 * * midnight on the 1st of every month
@reboot once at startup
Debug checklist when a cron job fails
- Is cron running? (
systemctl status cronorsystemctl status crond) - Is the job listed for the current user? (
crontab -l) - Is it executable (
chmod +x) and does it have a shebang? - Are all paths absolute, and is
PATHset? - Is output redirected (
>> file 2>&1)? - Did cron start it? (
grep CRON /var/log/syslog) - Is the timezone what you expect? (
date,timedatectl)
Commands in the post target Linux (Debian/Ubuntu and RHEL-family). Where they differ, it is noted.