0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Cron Job in Bash: Simple Guide and Examples

Use crontab -e to edit your cron jobs in bash. Each line follows the syntax minute hour day month weekday command to schedule commands automatically at set times.
📐

Syntax

The cron job syntax has six parts separated by spaces:

  • minute: 0-59
  • hour: 0-23
  • day: 1-31
  • month: 1-12
  • weekday: 0-7 (0 or 7 is Sunday)
  • command: The bash command or script to run

Use * to mean 'every' unit of time.

bash
* * * * * /path/to/command
💻

Example

This example runs a bash script every day at 7:30 AM.

bash
30 7 * * * /home/user/backup.sh
⚠️

Common Pitfalls

Common mistakes include:

  • Not using full paths for commands or scripts.
  • Forgetting to give execute permission to scripts.
  • Editing crontab without crontab -e which can cause errors.
  • Environment variables differ in cron, so commands may fail if relying on user environment.
bash
# Wrong: running script without full path
* * * * * ./backup.sh

# Right: use full path and ensure executable
* * * * * /home/user/backup.sh
📊

Quick Reference

Tips for using cron jobs:

  • Use crontab -l to list current cron jobs.
  • Use crontab -r to remove all cron jobs.
  • Redirect output to a file for debugging, e.g., * * * * * /script.sh >> /tmp/log.txt 2>&1.
  • Use @reboot to run a command once at startup.

Key Takeaways

Edit cron jobs with crontab -e to schedule bash commands.
Use full paths and ensure scripts have execute permission.
Cron uses a simple time syntax: minute, hour, day, month, weekday, then command.
Redirect output to files to catch errors and debug cron jobs.
Remember environment variables in cron are limited compared to your shell.