Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Pro

Cron and scheduling

A script that runs only when you remember to run it isn't automation yet. cron runs commands on a schedule: nightly backups, hourly reports, a cleanup every Sunday. It's on every Linux server, and its schedule syntax is reused by GitHub Actions, Kubernetes CronJobs and most cloud schedulers.

The crontab

Each user has a crontab (cron table): a list of schedules and commands.

bash
crontab -l     # list your jobs
crontab -e     # edit them (opens your editor)
crontab -r     # remove ALL your jobs (careful!)

Every line has five time fields and then the command:

┌───────────── minute        (0–59)
│ ┌─────────── hour          (0–23)
│ │ ┌───────── day of month  (1–31)
│ │ │ ┌─────── month         (1–12 or jan–dec)
│ │ │ │ ┌───── day of week   (0–7, 0 and 7 are Sunday, or sun–sat)
│ │ │ │ │
* * * * *  command to run
Field value Meaning
* Every value
5 Exactly 5
1,15 1 and 15
9-17 9 to 17
*/15 Every 15 (0, 15, 30, 45)
1-5 (day of week) Monday to Friday

Examples

Schedule Runs
*/5 * * * * Every 5 minutes
0 * * * * Every hour, on the hour
30 2 * * * Every day at 02:30
0 9 * * 1-5 09:00 on weekdays
0 0 1 * * Midnight on the 1st of every month
0 3 * * 0 03:00 every Sunday
0 */6 * * * Every 6 hours (00:00, 06:00, 12:00, 18:00)
@reboot Once, when the machine starts
@daily / @hourly / @weekly Shortcuts for 0 0 * * * / 0 * * * * / 0 0 * * 0

💡 Can't remember the order? crontab.guru explains any schedule in plain English.

⚠️ If you set both day of month and day of week (0 0 13 * 5), cron runs when either matches: every 13th and every Friday, not just Friday the 13th.

Installing a job

crontab -e opens an editor. In scripts, install jobs without an editor by piping a new table into crontab -:

bash
service cron start > /dev/null
cat > backup.sh <<'EOF'
#!/usr/bin/env bash
echo "backup ran at $(date -u +%H:%M:%S)" >> /tmp/backup.log
EOF
chmod +x backup.sh
( crontab -l 2>/dev/null; echo "* * * * * $PWD/backup.sh" ) | crontab -
crontab -l
Output
* * * * * /home/you/backup.sh

( crontab -l; echo "new line" ) | crontab - keeps the existing jobs and adds one. (Running crontab - with only the new line would replace them all.)

Here's the job running for real, a couple of minutes later:

bash
sleep 125
cat /tmp/backup.log | sed 's/[0-9][0-9]:[0-9][0-9]:/HH:MM:/'
Output
backup ran at HH:MM:01
backup ran at HH:MM:01

Cron starts each job right at the beginning of every matching minute. (The sed hides the real hours and minutes.)

Cron's environment is tiny

The #1 cron surprise: "it works in my terminal, but not in cron". Cron runs jobs with almost no environment: a minimal PATH, no ~/.bashrc, your home folder as the working directory, and /bin/sh as the shell.

bash
( crontab -l; echo '* * * * * env | sort > /tmp/cron-env.txt' ) | crontab -
sleep 65
cat /tmp/cron-env.txt
Output
HOME=/root
LANG=C.UTF-8
LOGNAME=root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
PWD=/root
SHELL=/bin/sh

Notice what's missing: your ~/.bashrc never ran (no aliases, no nvm, pyenv or conda setup), the shell is /bin/sh rather than Bash, and the job starts in the home folder. Ubuntu fills PATH from /etc/environment; on many other systems cron's PATH is just /usr/bin:/bin. Either way, programs in ~/bin, ~/.local/bin or ~/.nvm aren't found. Fixes:

  1. Use full paths in cron jobs and scripts: /usr/bin/python3, /home/deploy/app/backup.sh. Find them with command -v python3.
  2. Set variables at the top of the crontab; they apply to every job below:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""
  1. cd to the right folder inside the script, or use absolute paths for every file it touches.

Capturing output

Cron tries to email anything a job prints, which on most servers goes nowhere. Redirect output to a log file instead:

# m  h  dom mon dow  command
30   2  *   *   *    /home/deploy/bin/backup.sh >> /var/log/backup.log 2>&1

Inside the script, timestamp each line so the log is useful:

bash
log() { printf '%s %s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')" "$*"; }
log "backup started"
log "backup finished: 3 files"
Output
2026-11-22 09:21:26 backup started
2026-11-22 09:21:26 backup finished: 3 files

Don't let jobs overlap

If a job runs every 5 minutes but sometimes takes 7, two copies run at once and can corrupt each other's work. flock makes sure only one runs:

bash
flock -n /tmp/sync.lock -c 'echo "first copy running"; sleep 2' &
sleep 0.5
flock -n /tmp/sync.lock -c 'echo "second copy running"' || echo "second copy skipped: still locked"
wait
Output
first copy running
second copy skipped: still locked

In a crontab: */5 * * * * flock -n /tmp/sync.lock /home/deploy/bin/sync.sh.

A complete nightly backup job

backup-db.sh
#!/usr/bin/env bash
# Nightly: archive the app's data folder, keep the last 7 archives.
set -euo pipefail

src=${SRC:-$HOME/app-data}
dest=${DEST:-$HOME/backups}
keep=7

log() { printf '%s %s\n' "$(date -u '+%F %T')" "$*"; }

mkdir -p "$dest"
archive="$dest/app-$(date -u +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$archive" -C "$(dirname "$src")" "$(basename "$src")"
log "created $(basename "$archive") ($(du -h "$archive" | cut -f1))"

# delete all but the newest $keep archives
mapfile -t old < <(ls -1t "$dest"/app-*.tar.gz | tail -n +$(( keep + 1 )))
for f in "${old[@]}"; do
  rm -- "$f"
  log "deleted old $(basename "$f")"
done
log "done: $(ls -1 "$dest" | wc -l) archive(s) kept"
bash
mkdir -p app-data && echo "orders" > app-data/orders.db
mkdir -p backups && for d in 01 02 03 04 05 06 07 08; do touch -d "2025-10-$d" "backups/app-202510$d-020000.tar.gz"; done
bash backup-db.sh | sed -E 's/^[0-9-]+ [0-9:]+/[time]/; s/app-2026[0-9]{4}-[0-9]{6}/app-NEW/'
Output
[time] created app-NEW.tar.gz (4.0K)
[time] deleted old app-20251002-020000.tar.gz
[time] deleted old app-20251001-020000.tar.gz
[time] done: 7 archive(s) kept

There were 8 old archives plus the new one; the 2 oldest were deleted. (The sed hides today's date and time.) The crontab line for it:

30 2 * * *  flock -n /tmp/backup.lock /home/deploy/bin/backup-db.sh >> /home/deploy/backup.log 2>&1

Other ways to schedule

Tool When to use it
cron Simple recurring jobs on one server
systemd timers Modern Linux alternative: logs in journalctl, runs missed jobs after downtime (Persistent=true), resource limits. See the Linux track's systemd lesson
at Run something once later: echo "./deploy.sh" | at 23:00
sleep / timeout Delays and time limits inside scripts: timeout 30 curl …
CI schedules GitHub Actions on: schedule: - cron: '0 3 * * *' (in UTC)
Kubernetes CronJob Scheduled containers in a cluster

All of them reuse the same five-field cron syntax.

Practice

  1. Write the cron schedule for: every 10 minutes during working hours (09:00–17:59) on weekdays.
  2. Add a job that appends the date and the system load (uptime) to ~/load.log every minute. Check it after 3 minutes, then remove it again.
  3. Wrap a job in flock so it can't overlap with itself.
  4. Make a cron job that fails (ls /nope) and capture its error in a log file with 2>&1.
✎ Check your understanding

1.What does 0 2 * * * mean?

2.A script works in your terminal but fails in cron with "command not found". Most likely cause?

3.Which schedule runs every 15 minutes?

4.How do you stop two copies of a cron job running at the same time?

← Error handling and debugging