DEV Community

Udara Dananjaya
Udara Dananjaya

Posted on

Working with Cron Jobs on Ubuntu

πŸ“… Cron Jobs in Ubuntu

Cron is a time-based job scheduler in Unix-like systems used to run scripts and commands automatically at scheduled times.

πŸ”§ Edit the Crontab

To create or edit cron jobs for the current user:

crontab -e
Enter fullscreen mode Exit fullscreen mode

⏱️ Common Cron Job Examples

Run a backup script daily at 2:30 AM:

30 2 * * * /home/youruser/backup.sh
Enter fullscreen mode Exit fullscreen mode

Run a script every minute, and log output and errors:

* * * * * /bin/bash /path/to/your/script.sh >> /path/to/logfile.log 2>&1
Enter fullscreen mode Exit fullscreen mode

Run a script daily at 1:00 AM:

0 1 * * * /bin/bash /path/to/your/script.sh >> /path/to/logfile.log 2>&1
Enter fullscreen mode Exit fullscreen mode

🧠 Cron Syntax Breakdown

* * * * * command_to_run
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ └──── Day of the week (0 - 7) (Sunday = 0 or 7)
β”‚ β”‚ β”‚ └────── Month (1 - 12)
β”‚ β”‚ └──────── Day of month (1 - 31)
β”‚ └────────── Hour (0 - 23)
└──────────── Minute (0 - 59)
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Cron Job Setup & Management

  • Make your script executable:
  chmod +x /path/to/your/script.sh
Enter fullscreen mode Exit fullscreen mode
  • List current cron jobs:
  crontab -l
Enter fullscreen mode Exit fullscreen mode
  • Remove all cron jobs for the user:
  crontab -r
Enter fullscreen mode Exit fullscreen mode
  • Check cron service status:
  systemctl status cron
Enter fullscreen mode Exit fullscreen mode
  • Debugging cron output in system logs (if enabled):
  grep CRON /var/log/syslog
Enter fullscreen mode Exit fullscreen mode

✏️ Changing the Default Text Editor in Ubuntu

Cron and Git (e.g., git commit) may invoke a text editor β€” by default, it's usually nano or vi. You can change this to something else, like vim or VS Code.


πŸ”Ή Option 1: Quick Swap with Alternatives

sudo update-alternatives --config editor
Enter fullscreen mode Exit fullscreen mode

Select your preferred editor from the list.


πŸ”Ή Option 2: Set EDITOR or VISUAL Environment Variables

  1. Open your shell config file (e.g., ~/.bashrc or ~/.zshrc)

  2. Add one of the following:

For Nano:

export EDITOR=nano
Enter fullscreen mode Exit fullscreen mode

For Vim:

export EDITOR=vim
export VISUAL=vim
Enter fullscreen mode Exit fullscreen mode
  1. Apply the changes:
source ~/.bashrc   # or ~/.zshrc
Enter fullscreen mode Exit fullscreen mode
  1. Confirm the default editor:
echo $EDITOR
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Final Notes & Tips

  • Always test your script manually before scheduling it with cron.
  • Use full paths for commands and scripts in cron jobs β€” cron runs in a minimal environment.
  • Log all output to a file for easy debugging.
  • Comment your crontab entries if you have multiple tasks.
  • Update or delete cron jobs as your project changes.

Top comments (0)