Master Daily Backups with Bash and Cron

Master Daily Backups with Bash and Cron

Ah, backups. The unsung heroes of the tech world. We don’t think about them much—until we need them. And when disaster strikes (because it always does, right when Mercury retrogrades), having a pristine backup can feel like divine intervention. But let’s be honest: nobody wants to spend their mornings babysitting directories and running manual backups. That’s where the elegance of automation steps in, like a finely-tuned orchestra keeping our data safe while we sip our coffee.

Today, we’re pulling back the curtain on a little script that does the heavy lifting for you: a daily backup routine that will make you feel like a wizard of the command line. Let’s break down the magic, shall we?


Setting the Stage: The Backup Script

Our protagonist here is a Bash script named daily_backup.sh. This script is the first line of defense, responsible for swooping in every day to archive and safeguard our precious data. The script is like a diligent housekeeper, sweeping through directories, packing up files, and quietly removing the old to make room for the new.

But enough introduction—let’s take a peek behind the scenes.


2210+ FREE RESOURCES FOR DEVELOPERS!! ❤️😍🥳 (updated daily)
1400+ Free HTML Templates
317+ Free News Articles
60+ Free AI Prompts
285+ Free Code Libraries
49+ Free Code Snippets & Boilerplates for Node, Nuxt, Vue, and more!
25+ Free Open Source Icon Libraries
Visit dailysandbox.pro for free access to a treasure trove of resources!

Preparing for Action: The Date and Backup Directory

At the top of our script, we use Bash’s date command to capture the current date, formatted as YYYY-MM-DD. This date becomes part of our backup folder name, ensuring that each day’s backup gets its own neat little timestamped container. The script starts with a polite “hello,” creating a backup folder for the day:

DATE=$(date +'%Y-%m-%d')
BACKUP_DIR_BASE="/mnt/backup"
BACKUP_DIR="$BACKUP_DIR_BASE/$DATE"

echo "Making backup folder for $DATE"
mkdir -p "$BACKUP_DIR"

Simple, right? Just a little directory organization to keep things clean. After all, if you’re going to be running backups every day, you might as well keep them neatly labeled.


The Elegant Logging Function

A script without logging is like a diary without entries: silent and mysterious. To keep track of what our script is up to, we define a log() function that timestamps each message:

log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1"
}

Every log entry is a time-stamped breadcrumb, letting us know when each part of the backup process ran and if any hiccups occurred along the way. If something goes wrong, we’ll have a play-by-play account of the drama.


The Backup Routine: Archiving Our Data

Our backup script has two primary missions: to compress and archive our sites and scripts directories. Using tar and the power of gzip compression, it creates beautifully compact .tar.gz files:

# Backup Sites Directory
log "Backing up $SOURCE_DIR_1"
tar -czf $BACKUP_DIR/sites_$DATE.tar.gz $SOURCE_DIR_1 || { log "Failed to backup $SOURCE_DIR_1"; exit 1; }
log "$SOURCE_DIR_1 backup completed successfully."

# Backup Scripts Directory
log "Backing up $SOURCE_DIR_2"
tar -czf $BACKUP_DIR/scripts_$DATE.tar.gz $SOURCE_DIR_2 || { log "Failed to backup $SOURCE_DIR_2"; exit 1; }
log "$SOURCE_DIR_2 backup completed successfully."

Here’s where the real magic happens. If anything goes wrong—say, a directory refuses to cooperate—the script logs an error and gracefully exits, sparing us from a cascade of failures. But when things go well (which they should), we get a satisfying confirmation that the backup was a success.


The Cleanup Crew: Removing Old Backups

Even the best housekeepers know you have to take out the trash. Our script finishes its duties by deleting backups older than five days:

find "$BACKUP_DIR_BASE/" -type d -mtime +5 -exec rm -rf {} \;

This line ensures our backup storage doesn’t turn into a digital hoarder’s paradise. Only the freshest, most relevant backups get to stick around, while the rest are lovingly shown the door.


Automation: The Cron Job Maestro

Now, what good is a backup script if it only runs when we remember to execute it? (Spoiler: it’s not very good.) Enter the cron job, the maestro that ensures our script performs its duties like clockwork, every day, without fail.

To set up our daily backup, we add a cron job:

0 2 * * * /path/to/daily_backup.sh

This line tells cron to run our script at 2:00 AM every day. Why 2:00 AM? Because it’s the perfect time, when the world is quiet and our servers are least likely to be overwhelmed by user activity. Our backups happen silently, in the dead of night, like ninjas.


The Beauty of Automation

And there you have it: a simple yet powerful setup that keeps our data safe and sound. With the combination of Bash, tar, and cron, we’ve created a self-sustaining backup routine that runs without complaint. It’s the kind of script you can set and forget, yet it will always be there, quietly doing its job, day in and day out.

So go ahead, take a moment to appreciate the elegant dance of automation. Pour yourself a cup of coffee, knowing your data is safe, and perhaps whisper a small word of gratitude to the humble cron job. After all, in the world of servers and data, a little automation can feel like a work of art.

For more tips on web development, check out DailySandbox and sign up for our free newsletter to stay ahead of the curve!