Posted on
Administration

Scheduling Tasks with Cron and Bash

Author
  • User
    Linux Bash
    Posts by this author
    Posts by this author

Scheduling tasks using cron and Bash is a powerful way to automate repetitive tasks. Here's a comprehensive guide:


1. What is Cron?

  • cron is a time-based job scheduler in Unix-like operating systems.

  • It executes commands or scripts at specified times and intervals.

  • Jobs are defined in a crontab file.


2. Crontab Basics

To edit, list, or remove cron jobs:

  • Edit crontab:

    crontab -e
    
  • List current jobs:

    crontab -l
    
  • Remove all jobs:

    crontab -r
    

3. Crontab Syntax

Each line in the crontab file represents a task and follows this format:


* * * * * command_to_execute - - - - - | | | | | | | | | +---- Day of the week (0 - 7, Sunday is both 0 and 7) | | | +------ Month (1 - 12) | | +-------- Day of the month (1 - 31) | +---------- Hour (0 - 23) +------------ Minute (0 - 59)

4. Examples of Cron Schedules

  • Run every minute:

    * * * * * /path/to/script.sh
    
  • Run at 2:30 AM daily:

    30 2 * * * /path/to/script.sh
    
  • Run every Monday at 5:00 PM:

    0 17 * * 1 /path/to/script.sh
    
  • Run every 15 minutes:

    */15 * * * * /path/to/script.sh
    
  • Run at 3:00 AM on the 1st of every month:

    0 3 1 * * /path/to/script.sh
    

5. Writing and Scheduling Bash Scripts

Here’s how to integrate a Bash script with cron:

Step 1: Write the Script

Example: A script to back up a directory:

#!/bin/bash

# Variables
SOURCE="/home/user/documents"
DESTINATION="/backup/documents_$(date +%Y%m%d%H%M%S).tar.gz"

# Create the backup
tar -czf $DESTINATION $SOURCE

# Log the result
echo "$(date): Backup created at $DESTINATION" >> /var/log/backup.log

Save this script as /home/user/backup.sh.


Step 2: Make the Script Executable

chmod +x /home/user/backup.sh

Step 3: Schedule the Script with Cron

Edit the crontab:

crontab -e

Add a job to run the script daily at 1:00 AM:

0 1 * * * /home/user/backup.sh

6. Redirect Output and Errors

By default, cron sends email notifications for output. You can redirect output to a log file instead:

0 1 * * * /home/user/backup.sh >> /var/log/backup.log 2>&1

7. Use Environment Variables in Crontab

Cron jobs may not have the same environment as your user shell. Add environment variables at the top of your crontab:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

8. Advanced Features

Use cron.d for System-Wide Cron Jobs

  • Create a file in /etc/cron.d:

    sudo nano /etc/cron.d/myjob
    
  • Add a cron job with a user:

    0 1 * * * root /home/user/backup.sh
    

Cron Special Strings

  • @reboot: Run once after reboot.

    @reboot /home/user/startup.sh
    
  • @daily: Run once daily.

    @daily /home/user/daily-task.sh
    
  • @hourly: Run every hour.

    @hourly /home/user/hourly-task.sh
    

9. Debugging Cron Jobs

  • Ensure the script runs manually:

    /path/to/script.sh
    
  • Check the cron daemon log (may vary by distribution):

    sudo journalctl -u cron
    
  • Add logging to the script for debugging:

    echo "Cron job started at $(date)" >> /path/to/logfile.log
    

10. Combining Multiple Tasks

You can define multiple tasks in a single script and schedule the script with cron. For example:

#!/bin/bash
# Task 1: Clear temporary files
rm -rf /tmp/*

# Task 2: Sync files to a remote server
rsync -avz /home/user/files/ user@remote:/backup/

This guide should cover everything needed to schedule tasks using cron and Bash.

Further Reading

To expand your knowledge on scheduling tasks with Cron and Bash, you can further explore the following resources:

  1. CronHowTo - A detailed guide on using Cron, including common tasks and troubleshooting.

  2. Advanced Bash-Scripting Guide - An in-depth exploration of Bash scripting capabilities.

  3. Crontab Guru - A simple but powerful tool for checking cron schedule expressions.

  4. Using Cron and Crontab - A blog post dedicated to examples and best practices in managing cron jobs.

  5. Unix Shell Scripting Tutorial - Using Cron - A tutorial that goes deeper into scripting for automation and how to schedule these scripts efficiently.

These resources provide a combination of practical examples, theoretical knowledge, and troubleshooting tips to help you effectively use cron and Bash for automation and task scheduling.