How to Schedule Tasks Using Crontab in Bash
Use the
crontab -e command to open the cron table editor and add a line with the schedule and bash command you want to run. The format is minute hour day month weekday command, which lets you specify when and how often the task runs.Syntax
The crontab entry format has six parts separated by spaces:
- minute: 0-59
- hour: 0-23
- day: 1-31 (day of the month)
- month: 1-12
- weekday: 0-7 (0 or 7 is Sunday)
- command: The bash command or script to run
Each time field can be a number, a range (e.g., 1-5), a list (e.g., 1,3,5), or an asterisk (*) meaning "every".
bash
* * * * * /path/to/command arg1 arg2
Example
This example runs a bash script every day at 7:30 AM. It shows how to edit crontab and schedule a task.
bash
# Open crontab editor crontab -e # Add this line inside the editor to run script daily at 7:30 AM 30 7 * * * /home/user/myscript.sh # Save and exit the editor (usually Ctrl+X, then Y, then Enter)
Output
no output on scheduling; the script runs automatically at 7:30 AM daily
Common Pitfalls
Common mistakes when using crontab include:
- Not using full paths for commands or scripts, causing "command not found" errors.
- Forgetting to make scripts executable with
chmod +x. - Not setting environment variables, so commands behave differently than in your shell.
- Editing crontab with the wrong user, so the task never runs.
Always test your commands manually before scheduling.
bash
# Wrong: relative path and no executable permission 30 7 * * * ./myscript.sh # Right: full path and executable script 30 7 * * * /home/user/myscript.sh
Quick Reference
| Field | Allowed Values | Description |
|---|---|---|
| minute | 0-59 | Minute of the hour |
| hour | 0-23 | Hour of the day |
| day | 1-31 | Day of the month |
| month | 1-12 | Month of the year |
| weekday | 0-7 | Day of the week (0 or 7 is Sunday) |
| command | string | Command or script to execute |
Key Takeaways
Use
crontab -e to edit your scheduled tasks safely.Specify the schedule with five time fields followed by the bash command.
Always use full paths and make scripts executable to avoid errors.
Test commands manually before adding them to crontab.
Remember that environment variables in crontab may differ from your shell.