Keeping your important files safe is crucial. While cloud services are great, having a local, automated backup gives you full control and quick access. In this tutorial, we’ll build a simple but powerful backup solution using two classic Linux tools: bash for scripting and rsync for efficient file synchronization.
By the end, you’ll have a script that automatically backs up a directory of your choice on a schedule you set. Let’s get started!
Prerequisites
- A Linux-based operating system (like Ubuntu, Debian, or CentOS).
- Basic familiarity with the command line.
rsyncinstalled. Most systems have it, but if not, install it withsudo apt-get install rsync(for Debian/Ubuntu) orsudo yum install rsync(for CentOS/RHEL).
Step 1: The Core Command with `rs…
Keeping your important files safe is crucial. While cloud services are great, having a local, automated backup gives you full control and quick access. In this tutorial, we’ll build a simple but powerful backup solution using two classic Linux tools: bash for scripting and rsync for efficient file synchronization.
By the end, you’ll have a script that automatically backs up a directory of your choice on a schedule you set. Let’s get started!
Prerequisites
- A Linux-based operating system (like Ubuntu, Debian, or CentOS).
- Basic familiarity with the command line.
rsyncinstalled. Most systems have it, but if not, install it withsudo apt-get install rsync(for Debian/Ubuntu) orsudo yum install rsync(for CentOS/RHEL).
Step 1: The Core Command with rsync
The heart of our backup system is rsync (remote sync). It’s a utility for efficiently transferring and synchronizing files. It only copies the parts of files that have changed, making it incredibly fast after the initial backup.
The basic command structure is: rsync [options] <source> <destination>
Let’s build our command. Open your terminal and try this (remember to replace the paths with your own):
rsync -avz --delete /home/user/documents/ /mnt/backups/documents_backup/
Let’s break down those options:
-a(archive mode): This is a magic flag that does a lot. It preserves permissions, ownership, timestamps, and more. It’s equivalent to-rlptgoD.-v(verbose): Shows you which files are being copied. It’s great for seeing what’s happening.-z(compress): Compresses file data during the transfer, which can speed up transfers over a network or for large files.--delete: This is key for a mirror backup. It deletes files in the destination if they have been deleted from the source. Use with caution! It ensures the backup is an exact replica of the source.
The trailing slashes (/) are important! /source/ tells rsync to copy the contents of the source directory, not the directory itself.
Step 2: Create the Bash Script
Running that command manually works, but we want to automate it. Let’s create a bash script.
Create a new file named backup.sh:
touch backup.sh
Now, open it in your favorite text editor (like nano, vim, or code) and add the following content.
#!/bin/bash
# --- Configuration ---
SOURCE_DIR="/home/user/documents"
BACKUP_DIR="/mnt/backups/documents_backup"
LOG_FILE="/var/log/simple_backup.log"
DATE=$(date +"%Y-%m-%d %T")
# --- Main Script ---
# Make sure the backup directory exists
mkdir -p "$BACKUP_DIR"
echo "----------------------------------------" >> "$LOG_FILE"
echo "$DATE: Backup process started." >> "$LOG_FILE"
# The rsync command with output redirection for logging
rsync -avz --delete "$SOURCE_DIR/" "$BACKUP_DIR/" >> "$LOG_FILE" 2>&1
# Check the exit status of rsync
if [ $? -eq 0 ]; then
echo "$DATE: Backup completed successfully." >> "$LOG_FILE"
else
echo "$DATE: Backup FAILED. Check rsync errors above." >> "$LOG_FILE"
fi
What’s happening in this script?
#!/bin/bash: This “shebang” tells the system to execute this file with bash.- Configuration Variables: We define the source, destination, and a log file at the top. This makes the script easy to modify later.
mkdir -p: This command ensures the backup directory exists before we try to copy files into it. The-pflag prevents errors if the directory already exists.echo ... >> "$LOG_FILE": We write a timestamped start message to our log file. The>>appends the text to the file instead of overwriting it.- The
rsynccommand: This is our core command from Step 1, but now it uses variables. >> "$LOG_FILE" 2>&1: This is important. It redirects both the standard output (>>) and standard error (2>&1) to our log file. This means all messages, including errors, are captured.if [ $? -eq 0 ]: We check the exit code of the last command (rsync). A code of0means success. We log a success or failure message accordingly.
Step 3: Make the Script Executable
Right now, your backup.sh file is just a text file. You need to give it permission to be executed.
chmod +x backup.sh
Now you can run your backup script directly from the terminal:
./backup.sh
Check your log file (/var/log/simple_backup.log) to see the results. You might need sudo to view this file depending on permissions.
Step 4: Automate with Cron
The final step is to make this script run automatically. We’ll use cron, the standard Linux job scheduler.
To edit your personal “crontab” (a file that lists scheduled jobs), run:
crontab -e
If it’s your first time, you may be asked to choose a text editor.
Now, add the following line to the bottom of the file. Make sure to use the full, absolute path to your script. You can find it by running realpath backup.sh in the directory where you saved your script.
0 2 * * * /home/user/scripts/backup.sh
Let’s break down this cron schedule:
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ └---- Day of the week (0 - 7) (Sunday is 0 or 7)
│ │ │ └------- Month (1 - 12)
│ │ └---------- Day of the month (1 - 31)
│ └------------- Hour (0 - 23)
└---------------- Minute (0 - 59)
So, 0 2 * * * means “run this at minute 0 of hour 2, every day, every month, every day of the week.” In simple terms: run at 2:00 AM every day.
Save and close the crontab file. Your automated backup system is now live!
Conclusion
You’ve successfully created a robust, automated backup system with just a few lines of bash and some powerful Linux tools.
To recap:
- We used
rsyncto efficiently mirror a directory. - We wrapped it in a
bashscript with variables and logging. - We made it executable with
chmod. - We scheduled it to run daily with
cron.
As a next step, you could adapt this script to back up to a remote server by changing the BACKUP_DIR to an SSH target, like user@yourserver.com:/path/to/backups. rsync handles this beautifully over SSH without any extra work. Happy scripting!