0
0
Linux CLIscripting~5 mins

Common cron expressions in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Cron expressions let you schedule tasks to run automatically at specific times. They help you automate repetitive jobs like backups or updates without needing to start them manually.
When you want to run a backup script every day at midnight without forgetting.
When you need to send a report email every Monday morning automatically.
When you want to clear temporary files every hour to save disk space.
When you want to restart a service every Sunday at 3 AM to keep it fresh.
When you want to run a system update check every day at noon.
Commands
This command lists your current scheduled cron jobs so you can see what tasks are set to run.
Terminal
crontab -l
Expected OutputExpected
30 2 * * * /home/user/backup.sh 0 9 * * 1 /home/user/send_report.sh 0 * * * * /home/user/cleanup.sh
This command schedules the backup.sh script to run every day at midnight by adding it to your cron jobs.
Terminal
echo "0 0 * * * /home/user/backup.sh" | crontab -
Expected OutputExpected
No output (command runs silently)
- - Reads the cron job from standard input to set it as your crontab.
This opens your cron jobs in an editor so you can add, change, or remove scheduled tasks manually.
Terminal
crontab -e
Expected OutputExpected
No output (command runs silently)
This command removes all your scheduled cron jobs. Use it carefully to clear your cron schedule.
Terminal
crontab -r
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from cron expressions, remember: the five fields represent minute, hour, day of month, month, and day of week, in that order.

Common Mistakes
Using '*' in all fields without understanding it runs the job every minute.
This causes the task to run too often, which can overload your system.
Specify exact times or ranges for fields to control when the job runs.
Editing cron jobs without using 'crontab -e' or proper syntax.
This can corrupt your cron schedule or cause jobs not to run.
Always use 'crontab -e' or pipe valid cron lines with 'crontab -' to update jobs safely.
Forgetting that the day of week and day of month fields can both trigger the job.
This can cause jobs to run more often than expected if both fields match.
Use careful planning of these fields to avoid unintended runs.
Summary
Use 'crontab -l' to list current scheduled cron jobs.
Add new cron jobs by editing with 'crontab -e' or piping commands with 'crontab -'.
Understand the five fields in a cron expression: minute, hour, day of month, month, and day of week.