Backup and restore
Updated November 1, 2026
A backup only matters if you can restore from it. The test is to extract into a clean place and compare with the original.
tar czf backup.tar.gz -C ~ project
mkdir ~/restore && tar xzf backup.tar.gz -C ~/restore
diff -r ~/project ~/restore/project && echo OKSample output
$ tar czf backup.tar.gz -C ~ project
$ mkdir ~/restore && tar xzf backup.tar.gz -C ~/restore
$ echo extra > ~/project/notes.txt
$ diff -r ~/project ~/restore/project
Only in /home/student/project: notes.txt
$ echo $?
1
$ rm ~/project/notes.txt
$ diff -r ~/project ~/restore/project && echo OK
OKdiff -r compares two trees quietly; if it prints nothing, the contents match. For regular copies between machines people use rsync (that is the network, Part III).
Common mistakes
A typo in the directory name gives you an empty archive that passes every check. tar czf backup.tar.gz -C ~ Project prints tar: Project: Cannot stat: No such file or directory and exits with 2, yet the file appears: 45 bytes, gzip -t is happy, tar tzf prints nothing and returns 0. Check the exit code of tar itself, not whether a file showed up on disk.
tar czf backup.tar.gz . from inside the directory you are archiving gives tar: .: file changed as we read it and exit code 1: the archive grows inside the very directory tar is reading. Under set -euo pipefail the script stops on that line. Put the archive outside the tree you pack.
diff -r compares file contents and nothing else. A file that was owned by root:root becomes yours when you extract as a regular user: the mode -rw------- survives, the owner changes, and diff -r stays quiet and prints OK. Check ownership separately with ls -l, and restore system files with sudo tar xzf.
Used in
You need this in the lesson Archives: tar and gzip.