Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Linux File Backup Script: A Practical Guide

· 6 min read · Home Tech

In this article
  1. Why You Need a Backup Script
  2. Core Tools for Backup Scripts
  3. Writing a Basic Backup Script
  4. Scheduling with Cron
  5. Choosing What to Back Up
  6. Common Problems and Solutions
  7. Comparing rsync and tar
  8. Safety and Testing
  9. Frequently Asked Questions

A Linux file backup script is a shell script that automates copying or archiving files and directories to a safe location, protecting against data loss from hardware failure, accidental deletion, or corruption. This guide explains how to write, use, and customize such scripts, covering common tools, scheduling, and best practices.

Why You Need a Backup Script

Manual backups are easy to forget, especially when you're busy. A script ensures backups happen consistently, whether daily, weekly, or in real time. It also reduces human error—you don't have to remember which folders to copy or where to put them. For anyone running a home server, a development machine, or a business system, a backup script is the first line of defense against data loss.

Core Tools for Backup Scripts

Linux offers several command-line tools commonly used in backup scripts. The right choice depends on your needs:

  • cp – Simple file copying; good for small, infrequent backups.
  • rsync – The most popular choice; copies only changed files, supports remote destinations, and preserves permissions and timestamps.
  • tar – Creates a single archive file, often compressed with gzip or bzip2; ideal for long-term storage.
  • dd – Low-level block copy; used for cloning disks or partitions, not for regular file backups.

For most users, rsync is the sweet spot—it's fast, flexible, and widely available. tar is better when you want a single compressed file to move to an external drive or cloud storage.

Writing a Basic Backup Script

A backup script is just a text file with a sequence of commands. Here's a simple example using rsync:

#!/bin/bash
BACKUP_DIR="/home/user/backups"
SOURCE="/home/user/Documents"
rsync -av --delete "$SOURCE" "$BACKUP_DIR/"

Save this as backup.sh, make it executable with chmod +x backup.sh, and run it with ./backup.sh. The -a flag preserves permissions, timestamps, and other metadata; -v shows progress; --delete removes files in the backup that were deleted from the source, keeping them in sync.

For a tar-based backup, the script might look like:

#!/bin/bash
BACKUP_FILE="/home/user/backups/backup-$(date +%Y%m%d).tar.gz"
tar -czf "$BACKUP_FILE" /home/user/Documents

The $(date +%Y%m%d) adds a date stamp to the filename, so each backup is unique.

Scheduling with Cron

To run a backup automatically, use cron, the built-in job scheduler. Edit your crontab with crontab -e and add a line like:

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

This runs the script every day at 2:00 AM. The five fields are minute, hour, day of month, month, and day of week. Common schedules:

  • Daily at 3 AM: 0 3 * * *
  • Weekly on Sunday at 4 AM: 0 4 * * 0
  • Every hour: 0 * * * *

Make sure the script has a shebang (#!/bin/bash) and execute permissions, or cron won't run it.

Choosing What to Back Up

Not everything needs to be backed up. Focus on irreplaceable data:

  • Home directories (documents, photos, config files)
  • Databases (MySQL, PostgreSQL) – use their export tools first
  • Web server content (e.g., /var/www)
  • Application configuration files (e.g., /etc)

Exclude temporary files, caches, and system directories that can be reinstalled. With rsync, use the --exclude option:

rsync -av --exclude='*.tmp' --exclude='cache/' /home/user /backup/

For databases, don't just copy the data files—use mysqldump or pg_dump to create a consistent export, then back up that file.

Common Problems and Solutions

Backup scripts often fail silently. Here are frequent issues and how to handle them:

  • Permissions errors – Running as a regular user may not allow reading certain files. Use sudo carefully, or ensure the script runs with appropriate privileges.
  • Disk full – Check available space before starting; add a check like df -h and abort if space is low.
  • No notification on failure – Add error handling with set -e to exit on any error, and send an email using mail or a system notification.
  • Backup not rotating – Old backups accumulate. Use a rotation script to keep only the last N backups (e.g., delete files older than 30 days with find).

Example rotation command:

find /backup -name '*.tar.gz' -mtime +30 -delete

This deletes backups older than 30 days.

Comparing rsync and tar

Both tools have strengths. Here's a quick comparison:

  • rsync – Incremental (only transfers changed parts), works over network with SSH, preserves hard links and permissions. Best for ongoing backups to a mounted drive or remote server.
  • tar – Creates a single file, easy to compress and move, but each run creates a full copy unless you use incremental features (which are more complex). Best for periodic snapshots.

Many users combine them: use rsync for a local mirror, then tar the mirror to create a compressed archive for off-site storage.

Safety and Testing

A backup is only useful if you can restore from it. Test your backups regularly by restoring a few files to a temporary location. Also, follow the 3-2-1 rule: keep at least three copies, on two different media, with one off-site. Your script should handle the copying; you handle the verification.

Be careful with --delete in rsync—if you point the source and destination backwards, you'll delete files from your source. Always double-check paths.

Frequently Asked Questions

How do I back up to an external drive?

Mount the drive (e.g., mount /dev/sdb1 /mnt/backup), then use rsync with the mount point as the destination. Add the mount command to your script or rely on system automounting. Ensure the drive is mounted before the backup runs, or the script will fail.

Can I back up over the network?

Yes. Rsync works over SSH: rsync -av /home/user user@remote:/backup/. You'll need SSH keys set up for passwordless operation. This is a secure and efficient way to keep an off-site copy.

What's the difference between a backup and a sync?

A backup is a copy you can restore from if the original is lost. A sync makes two locations identical, which means if you accidentally delete a file from the source, it's deleted from the sync destination too. For backups, use rsync with --delete only if you want the backup to mirror the source exactly; otherwise, omit it to keep deleted files.

How do I encrypt my backups?

Use GPG to encrypt a tar archive: tar -czf - /home/user | gpg -c > backup.tar.gz.gpg. Or use rsync over SSH, which is already encrypted. For cloud storage, consider tools like restic or BorgBackup that have built-in encryption.

Why is my cron job not running?

Check that the script is executable (chmod +x), the shebang is correct, and the cron syntax is valid. Also check the cron log (grep CRON /var/log/syslog) and make sure the script doesn't produce errors that go unnoticed. Redirect output to a log file to debug.

Should I use a backup tool instead of a script?

Tools like restic, BorgBackup, and Duplicity offer encryption, deduplication, and cloud support out of the box. For simple needs, a script is fine. For large or critical systems, a dedicated tool may save time and provide more reliability.