Bash Script Automation and Scheduling
The real power of Bash scripting comes from automation — running tasks without manual effort. From automated backups to scheduled cleanups, Bash scripts combined with the Linux scheduler (cron) allow any repetitive task to run automatically at a chosen time.
What Is Automation?
Automation means writing a script once and letting the system run it on a schedule or trigger. Manual tasks that take time every day become zero-effort background jobs.
┌─────────────────────────────────────────────────────┐ │ │ │ Without Automation: │ │ Developer → Opens terminal daily → Runs backup │ │ → Waits for completion → Logs result │ │ │ │ With Automation: │ │ Script + Cron Job → Runs at 2:00 AM every night │ │ → Backs up, logs, and exits │ │ → Developer sleeps peacefully │ │ │ └─────────────────────────────────────────────────────┘
Writing a Reusable Automation Script
Example – Automated Backup Script
#!/bin/bash set -euo pipefail # Configuration SOURCE_DIR="/home/john/documents" BACKUP_DIR="/home/john/backups" DATE=$(date +%Y-%m-%d_%H-%M-%S) BACKUP_FILE="backup_$DATE.tar.gz" LOGFILE="/home/john/backups/backup.log" # Create backup directory if it does not exist mkdir -p "$BACKUP_DIR" # Create compressed archive tar -czf "$BACKUP_DIR/$BACKUP_FILE" "$SOURCE_DIR" # Log result echo "[$DATE] Backup created: $BACKUP_FILE" >> "$LOGFILE" echo "Backup complete: $BACKUP_DIR/$BACKUP_FILE"
Making a Script Executable and Portable
chmod +x backup.sh
Run with full path (important for cron jobs):
/home/john/scripts/backup.sh
Always use full paths inside automation scripts. Cron jobs do not have the same PATH as an interactive shell, so commands like tar, grep, and python3 must use absolute paths like /bin/tar or /usr/bin/python3.
Introduction to Cron
cron is the Linux task scheduler. It runs commands or scripts automatically at scheduled times. The schedule is defined in a file called the crontab.
Open the Crontab Editor
crontab -e
View Current Cron Jobs
crontab -l
Remove All Cron Jobs
crontab -r
Crontab Syntax
┌────────────────────────────────────────────────────────────┐ │ │ │ * * * * * /path/to/script.sh │ │ │ │ │ │ │ │ │ │ │ │ │ └── Day of week (0–7, 0 and 7 = Sunday) │ │ │ │ │ └──── Month (1–12) │ │ │ │ └────── Day of month (1–31) │ │ │ └──────── Hour (0–23) │ │ └────────── Minute (0–59) │ │ │ │ * means "every" │ └────────────────────────────────────────────────────────────┘
Cron Schedule Examples
| Cron Expression | Meaning |
|---|---|
* * * * * | Every minute |
0 * * * * | Every hour at minute 0 |
0 2 * * * | Every day at 2:00 AM |
0 2 * * 0 | Every Sunday at 2:00 AM |
0 0 1 * * | First day of every month at midnight |
*/5 * * * * | Every 5 minutes |
30 8 * * 1-5 | Monday to Friday at 8:30 AM |
@reboot | Once at system startup |
Crontab Entry Example – Nightly Backup
0 2 * * * /home/john/scripts/backup.sh >> /home/john/logs/cron.log 2>&1
This runs the backup script every night at 2:00 AM and logs all output (including errors) to cron.log.
Running Scripts at System Startup
@reboot /home/john/scripts/start_services.sh
Common Automation Script Patterns
Pattern 1 – Delete Old Log Files
#!/bin/bash # Delete log files older than 30 days find /var/log/myapp/ -name "*.log" -mtime +30 -delete echo "Old logs cleaned up on $(date)"
Pattern 2 – Disk Space Alert
#!/bin/bash
THRESHOLD=80
USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt $THRESHOLD ]; then
echo "ALERT: Disk usage is at ${USAGE}% on $(hostname)" | mail -s "Disk Alert" admin@example.com
fi
Pattern 3 – Auto-Restart a Service if Down
#!/bin/bash SERVICE="nginx" if ! systemctl is-active --quiet $SERVICE; then systemctl start $SERVICE echo "$(date): $SERVICE was down and has been restarted." >> /var/log/service_monitor.log fi
Environment Variables in Cron
Cron runs with a minimal environment. Commands that work in the terminal may fail in cron because the PATH variable is different. Set PATH explicitly at the top of crontab or the script.
# In crontab PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 0 2 * * * /home/john/scripts/backup.sh
at Command – Run Once at a Specific Time
The at command schedules a script to run once at a specific time — unlike cron which repeats.
at 10:30 PM tomorrow <<EOF /home/john/scripts/send_report.sh EOF
List pending at jobs:
atq
Remove a scheduled at job:
atrm job_number
Key Takeaways
- Cron is the Linux scheduler — use it to run scripts automatically at any time.
- Use
crontab -eto add, edit, or remove cron jobs. - Always use full paths for commands and files in cron jobs.
- Redirect cron output to a log file to capture success and error messages.
- Use
@rebootto run a script once when the system starts. - The
atcommand schedules a one-time job at a specific time.
