Skip to content

Automated File Backup

backupcron-readyrsync
5 min read
Matching toolCron Job Builder

Quick Answer

The cp command copies files and directories from one location to another. This script wraps cp -r with a date-stamped destination path, creating a new backup folder — like backup_2026-06-03_14-30 — each time it runs, so no backup overwrites a previous one. Without scheduled backups, a single accidental rm -rf or disk failure can permanently destroy days or weeks of work. There is no recycle bin on Linux servers. The script lets you set SOURCE (the folder to back up) and DEST (where backups are stored) at the top, then call it manually or schedule it with cron. A typical hourly backup of a 1 GB project folder completes in under five seconds. cp is part of coreutils on every Linux box and macOS, so there is nothing to install. Schedule with cron: 0 * * * * /home/user/backup.sh.

I was clearing space on the SSD — the usual end-of-month sweep of dead checkouts and node_modules graveyards — and I fired rm -rf at what I was sure was a throwaway directory. It wasn't. It was about two months of work on a side project, gone in the time it takes to press Enter. My first thought was relief: there's a backup somewhere. There wasn't. For months I'd been promising myself I'd "set up proper backups next week," and next week had never actually arrived, so the folder was nowhere — not on the 2 TB drive where backups are supposed to live, not anywhere else.

What stung wasn't the deletion itself. rm did exactly what I told it to. The real failure was that backups had stayed a future-tense intention instead of something that runs on its own, and an intention protects nothing. A backup only counts if it happens whether or not you remember it: a script, on a schedule, named so no run overwrites the last, writing to a different disk than the one you work on. The version below is what I wrote that same night, once I'd decided future-me didn't get to be trusted with two months of work ever again.

The backup script I wrote the night I lost a folder

Copy this, paste it into a file called backup.sh, and you're 90% done.

bash
#!/bin/bash # Script: backup.sh # Purpose: Prevent data loss from disk failure or accidental deletion with timestamped backups # Usage: ./backup.sh set -euo pipefail CHECK="✓" CROSS="✗" SOURCE="/home/user/documents" DEST="/backup" DATE=$(date +%Y-%m-%d_%H-%M) mkdir -p "$DEST" if cp -r "$SOURCE" "$DEST/backup_$DATE"; then echo "$CHECK Done. Saved to: $DEST/backup_$DATE" else echo "$CROSS Backup failed — check that $SOURCE exists and $DEST is writable" exit 1 fi

What this does, line by line

SOURCE is the folder you want to back up. DEST is where backups are saved. DATE grabs the current timestamp. mkdir -p creates the destination folder if it doesn't exist. cp -r copies everything recursively. The last line confirms it worked.

Setting it up so it actually runs

Step 1 — Create the file

Open a terminal and run:

bash
nano backup.sh

Paste the script above, then press Ctrl+X → Y → Enter to save.

Step 2 — Edit your paths

Change SOURCE to the folder you want to back up and DEST to where you want backups saved. Examples:

VariableExample valueWhat it means
SOURCE/home/alice/projectsThe folder being backed up
SOURCE/var/www/htmlA web server's files
DEST/backupA local backup directory
DEST/mnt/external-driveAn external drive mount point

Step 3 — Make it executable

bash
chmod +x backup.sh

You only need to do this once. It gives the script permission to run.

Step 4 — Run it

bash
./backup.sh

You should see: ✓ Done. Saved to: /backup/backup_2026-05-02_14-30

The create dated folder snippet explains the date format options in detail if you want to add seconds or change the separator for custom retention scripts.

Schedule It with Cron

Running this manually defeats the purpose. Here's how to make it run automatically every day. Backups are one piece of a server's baseline — see the bash scripts every sysadmin needs guide for the rest.

Open your crontab

bash
crontab -e

Add one of these lines

bash
# Run every day at 2am 0 2 * * * /home/user/backup.sh # Run every Sunday at midnight 0 0 * * 0 /home/user/backup.sh # Run every hour 0 * * * * /home/user/backup.sh

Tip: Use crontab.guru

Go to crontab.guru to build and test cron time expressions for free. It explains exactly when your job will run in plain English.

Three versions I keep around

Swap cp -r for rsync to only copy files that have changed. Much faster on big directories:

bash
#!/bin/bash SOURCE="/home/user/documents" DEST="/backup/latest" rsync -av --delete "$SOURCE/" "$DEST/" echo "✓ Sync complete: $(date)"

Log every backup to a file

Know exactly when each backup ran and whether it succeeded:

bash
#!/bin/bash SOURCE="/home/user/documents" DEST="/backup" DATE=$(date +%Y-%m-%d_%H-%M) LOG="/var/log/mybackup.log" mkdir -p "$DEST" cp -r "$SOURCE" "$DEST/backup_$DATE" && \ echo "[$DATE] SUCCESS: backup_$DATE" >> "$LOG" || \ echo "[$DATE] FAILED" >> "$LOG"

Keep only the last 7 backups

Prevent your backup folder from filling up your disk:

bash
#!/bin/bash SOURCE="/home/user/documents" DEST="/backup" DATE=$(date +%Y-%m-%d_%H-%M) KEEP=7 mkdir -p "$DEST" cp -r "$SOURCE" "$DEST/backup_$DATE" # Delete oldest backups, keep only the last $KEEP ls -dt "$DEST"/backup_* | tail -n +$(( KEEP + 1 )) | xargs rm -rf echo "✓ Backed up. Keeping last $KEEP snapshots."

Where backups quietly betray you

Missing trailing slash on rsync SOURCE

With rsync, rsync -av /source /dest/ copies the folder itself. rsync -av /source/ /dest/ copies the folder's contents. That trailing slash distinction matters significantly. When in doubt, test with --dry-run first.

Cron uses a different PATH

When scripts run manually but fail via cron, add PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin as the first line of your crontab, since cron doesn't load your shell's PATH.

Backing up to the same disk

A backup on the same physical disk as your source files won't save you from a drive failure. Use an external drive, a second machine, or a cloud location for real protection.

Frequently Asked Questions

How do I automatically back up files in Linux?

Use a bash script with cp -r or rsync to copy your folder to a backup location. Append a date variable like DATE=$(date +%Y-%m-%d_%H-%M) to the destination path so each backup gets a unique name, then add the script to cron to run it automatically.

How do I schedule a backup to run every day?

Open cron with crontab -e and add: 0 2 * * * /home/user/backup.sh — this runs at 2am daily. Use crontab.guru to build any cron expression you need.

What's the difference between cp and rsync for backups?

cp copies everything every time — simple but slow on large folders. rsync only transfers files that have changed, making it significantly faster for repeated backups of large directories. For daily backups of large directories, rsync is the right choice. For small folders or one-time copies, cp is fine. For MySQL or MariaDB, neither tool captures a consistent state during active writes — use the MySQL database backup script instead.

How do I verify my backup script is working?

Add set -x right after #!/bin/bash. This enables debug mode and prints every command as it runs, so you can see exactly what happened. Remove it once you're satisfied the script works correctly.

Part of the Backup & Recovery collection

BashSnippets logo

Written by Anguishe

Creator of BashSnippets.xyz

bashsnippets.xyz/about

Run this script on a real Linux server

Get $200 free credit — DigitalOcean

Get $200 Free →

Affiliate link · we earn a commission

Need a domain for your next project?

Register with Namecheap — free WHOIS privacy included

Check Domain Prices →

Affiliate link · we earn a commission

PAID RESOURCE — $9

The Production Bash Toolkit

6 scripts + shared library + 52-page field guide. The production layer the free snippets don't cover.

Get the Toolkit →

Related Snippets

Frequently Asked Questions

faq — snippet

How do I run this script?

Save as backup.sh, set SOURCE and DEST paths, run chmod +x backup.sh, then execute ./backup.sh.

faq — snippet

Does this work on macOS?

Yes. cp and rsync work on macOS. Use rsync for faster incremental backups on large folders.

faq — snippet

How do I automatically back up files in Linux?

Use a bash script with cp -r or rsync and append a date variable to the destination path so each backup gets a unique name.

faq — snippet

How do I schedule a backup to run every day?

Open cron with crontab -e and add: 0 2 * * * /home/user/backup.sh — this runs at 2am daily.