Bash Cron

Cron lets Linux run scripts automatically on a recurring schedule defined by crontab entries.

What Is Cron and How Do You Edit It?

Cron is a time-based job scheduler built into Linux and other Unix-like systems. A background daemon wakes up every minute, checks each user's crontab file for jobs that are due, and runs them with that user's shell and environment. You manage your own schedule with crontab -e, which opens your crontab in a text editor; crontab -l lists your current jobs, and crontab -r deletes your entire crontab without confirmation.

Example

# Edit your personal crontab
crontab -e

# List your current cron jobs
crontab -l

# Remove your entire crontab (use with caution)
crontab -r

Cron Schedule Syntax

Each crontab line has five time fields -- minute, hour, day of month, month, and day of week -- followed by the command to run. An asterisk * means "every value" for that field. Fields also accept ranges (1-5), lists (1,3,5), and step values (*/15) to express more complex schedules concisely.

FieldAllowed Values
Minute0-59
Hour0-23
Day of month1-31
Month1-12 (or JAN-DEC)
Day of week0-6, where Sunday is 0 (or SUN-SAT)
  • * * * * * -- runs every minute of every day
  • 0 * * * * -- runs once at the start of every hour
  • 0 9 * * 1-5 -- runs at 9:00 AM every weekday
  • */15 * * * * -- runs every 15 minutes
  • 0 0 1 * * -- runs at midnight on the first day of every month

Example

# Contents of a crontab file:

# Run a backup every day at 2:30 AM
30 2 * * * /home/alice/scripts/backup.sh

# Run a cleanup script every 15 minutes
*/15 * * * * /home/alice/scripts/cleanup.sh

# Send a weekly report every Monday at 8:00 AM
0 8 * * 1 /home/alice/scripts/weekly_report.sh

Example

#!/bin/bash
# backup.sh - a typical script run from cron
timestamp=$(date "+%Y-%m-%d %H:%M:%S")
log_file="/var/log/backup.log"

echo "[$timestamp] Backup started" >> "$log_file"
tar -czf "/backups/data_$(date +%F).tar.gz" /home/alice/data
echo "[$timestamp] Backup finished" >> "$log_file"
Note: Cron jobs run with a minimal environment and no interactive shell, so always use full, absolute paths to commands and files, and redirect output to a log file for debugging.
Note: crontab -r deletes your entire crontab instantly with no confirmation prompt. Run crontab -l > backup.cron first to save a copy before making risky edits.

Exercise: Bash Cron

What is the correct order of the five time fields in a crontab schedule?