Intermediate · 12 min · practise every command in the built-in terminal

rsync — Copies and Backups

cp copies everything, every time. rsync compares first and sends only what changed — and works over the network through ssh. That makes it the tool for backups, deploys and mirrors.

sudo apt install rsync
rsync -av ~/site/ ~/site-copy/
sending incremental file list
created directory /home/student/site-copy
./
index.html
menu.html
old-offer.html
css/
css/style.css
img/
img/logo.png

-a (archive) copies folders, permissions, times and links as they are; -v lists what it sends. Run it again: nothing is listed — nothing changed.

The slash at the end

CommandResult
rsync -av site/ dest/what's in site goes into dest
rsync -av site dest/dest/site/…

Mirrors: --delete

A file removed from the source stays in the copy — unless you add --delete. That deletes things, so look first with -n (dry run):

rm ~/site/old-offer.html
rsync -avn --delete ~/site/ ~/site-copy/
deleting old-offer.html
…
total size is 25,180  speedup is 128.47 (DRY RUN)

To another server

A backup on the same disk dies with the disk. This network has a backup server, backup01, and your key works there for the user backup:

rsync -av --delete ~/site/ backup@backup01:/srv/backups/site/
ssh backup@backup01 ls -l /srv/backups/site

USER@HOST:PATH — rsync goes through ssh, with your key.

Restore

The same command the other way round:

rsync -av backup@backup01:/srv/backups/site/ ~/restore/
OptionMeans
-aarchive: keep everything
-vlist what is sent
-ndry run: only show
--deleteremove what the source no longer has
--exclude='*.log'skip these
-zcompress on the way
-hhuman-readable sizes

💡 A nightly backup is this command in a script, run by a systemd timer (see systemd Timers).

Practice tasks

  1. Install rsync
  2. Copy ~/site to ~/site-copy with rsync
  3. Remove ~/site/old-offer.html, then preview a mirror with --delete — without changing anything
  4. Back the site up to backup01: /srv/backups/site/ as the user backup
  5. Look at the backup on the server
  6. Restore the backup into ~/restore

Commands in this lesson

Archives & Backups