The tar command, short for tape archive, remains the backbone of file archiving in Linux and Unix-like operating systems. Whether you are backing up configuration files, preparing source code for distribution, or moving a website directory to a new server, mastering tar is an essential skill for any system administrator or developer. Despite its age, it is the standard tool for bundling multiple files and directories into a single file, often called a tarball. This guide covers everything from basic archive creation to advanced compression, exclusion patterns, and automation techniques And that's really what it comes down to. And it works..
Understanding the Core Syntax
Before diving into specific examples, it helps to understand the standard syntax structure. The tar command operates on a specific order of operations: options, followed by the archive name, and finally the files or directories to include Surprisingly effective..
tar [options] [archive-file] [files-or-directories]
The most frequently used options form the acronym cvf (Create, Verbose, File), though modern usage often adds compression flags immediately after.
-cor--create: Creates a new archive.-vor--verbose: Displays the files being processed (highly recommended for verification).-for--file=ARCHIVE: Specifies the filename of the archive. This flag must be the last letter in the option cluster because it expects the filename immediately after it.-zor--gzip: Compresses the archive using gzip (.tar.gzor.tgz).-jor--bzip2: Compresses using bzip2 (.tar.bz2).-Jor--xz: Compresses using xz (.tar.xz), offering the highest compression ratio.
Creating a Basic Uncompressed Archive
The simplest use case is bundling files without compression. This is useful when speed is the priority and storage space is not a constraint, or when piping output to another tool.
To archive a directory named project_files into project_backup.tar:
tar -cvf project_backup.tar project_files
Breakdown of the command:
tar: Invokes the program.-cvf: Create (c), Verbose (v), File (f).project_backup.tar: The output filename (convention dictates the.tarextension).project_files: The source directory.
You will see a scrolling list of every file added. The resulting file preserves the directory structure, permissions, timestamps, and symbolic links exactly as they exist on the disk.
Creating Compressed Archives (The Standard Workflow)
In almost all production scenarios, you will want compression to save disk space and bandwidth. The three main algorithms offer different trade-offs between speed and compression ratio.
1. Gzip (-z) — The Universal Standard
Gzip is the most compatible and fastest option. It is the default choice for software distribution and general backups. The resulting files typically end in .tar.gz or .tgz Easy to understand, harder to ignore. Worth knowing..
tar -czvf project_backup.tar.gz project_files
2. Bzip2 (-j) — Better Compression, Slower Speed
Bzip2 creates smaller files than gzip but takes significantly longer to compress and decompress. Use this when archive size matters more than CPU time. Extensions: .tar.bz2, .tbz2 Still holds up..
tar -cjvf project_backup.tar.bz2 project_files
3. Xz (-J) — Maximum Compression
Xz (LZMA2) offers the best compression ratios, often 30–50% smaller than gzip, but is the slowest. It is the standard for distributing Linux kernel sources and software packages (.tar.xz).
tar -cJvf project_backup.tar.xz project_files
Pro Tip: Modern versions of
tarsupport auto-compression detection based on the file extension. xz,.lz4, and.You can simply runtar -cvf archive.Consider this: tar. gzsuffix. gz project_files(omitting-z), andtarwill automatically invoke gzip because of the.bz2,.And this works for. zstas well.
Preserving Permissions and Ownership (Critical for Backups)
By default, tar attempts to preserve permissions, but behavior changes based on the user executing the command Small thing, real impact..
- As a standard user:
tarsaves the owner and group names (or numeric IDs) but cannot restore ownership to a different user upon extraction unless run as root. - As root (sudo):
tarpreserves everything: ownership (UID/GID), permissions (mode), timestamps, and extended attributes (ACLs, SELinux contexts).
For a true system-level backup (e.g., /etc, /home, /var/www), always run with sudo and use the -p (preserve permissions) flag explicitly, though it is implied when running as root.
sudo tar -cpzvf system_backup.tar.gz /etc /home /var/www
-p/--preserve-permissions: Extracts all permission information (owner, group, mode, flags). Essential for restoring system state.
Excluding Files and Directories
Real-world directories contain cache files, version control folders (.That said, git), node_modules, virtual environments (venv), and temporary files that bloat archives unnecessarily. The --exclude flag is indispensable Surprisingly effective..
Exclude Specific Patterns
tar -czvf project_clean.tar.gz project_files \
--exclude='*.log' \
--exclude='node_modules' \
--exclude='.git' \
--exclude='__pycache__' \
--exclude='*.tmp'
Exclude from a File List
For complex projects with many exclusion rules, maintain a text file (e.g., backup_exclude.txt) listing patterns, one per line:
*.log
node_modules
.git
venv
*.swp
Then reference it using -X (capital X):
tar -czvf project_clean.tar.gz -X backup_exclude.txt project_files
Important Syntax Note: Place --exclude or -X after the source directory path in some older tar versions, though GNU tar (standard on Linux) is generally flexible. Placing excludes before the source is the safest, most portable habit.
Handling Absolute vs. Relative Paths
A common "gotcha" for beginners involves absolute paths.
The Problem
If you run:
tar -czvf /backups/full_etc.tar.gz /etc
The archive stores the absolute path /etc. When you extract this on a new server, tar will try to write files directly to the root /etc, potentially overwriting the live system configuration. This is dangerous Still holds up..
The Solution: Change Directory (-C)
Use the -C flag to change to the parent directory before archiving, storing only relative paths.
tar -czvf /backups/full_etc.tar.gz -C / etc
-C /: Changes the working directory to root/.etc: The relative target.
Now, the archive contains etc/passwd, etc/nginx/, etc. That said, you can safely extract this into a temporary folder (mkdir restore && tar -xzf full_etc. tar.gz -C restore) to inspect files before moving them into place.
Splitting Large Archives for Storage Limits
Filesystems (like FAT32) or backup media (DVDs, specific cloud upload limits) may restrict maximum file sizes. tar pipes perfectly into the split command And it works..
Create a compressed archive and split
Create a compressed archive and split it into 2GB chunks (adjust 2G as needed for your media):
tar -czf - /home/user/data | split -b 2G - /backups/data_backup.tar.gz.part
tar -czf -: Writes the.tar.gzstream to stdout (the hyphen-).split -b 2G -: Reads from stdin and writes output files nameddata_backup.tar.gz.partaa,data_backup.tar.gz.partab, etc.
To restore, reverse the pipe:
cat /backups/data_backup.tar.gz.part* | tar -xzvf - -C /restore_location
Incremental Backups with Snapshots
For daily backups of large datasets, full archives are wasteful. GNU tar supports incremental backups using a snapshot file (.snar), which records metadata (inodes, timestamps) to detect changed files.
Level 0 (Full Baseline)
tar -czvf /backups/backup_level0.tar.gz \
--listed-incremental=/backups/backup.snar \
/home/user/data
This creates the initial full archive and the backup.snar index file.
Level 1+ (Incremental)
Run the exact same command daily (or via cron). tar reads the .snar file, compares the filesystem state, and appends only new/modified files to a new archive Not complicated — just consistent. Worth knowing..
tar -czvf /backups/backup_inc_$(date +%F).tar.gz \
--listed-incremental=/backups/backup.snar \
/home/user/data
Restoring an Incremental Set: You must restore in order: Level 0 first, then each incremental layer sequentially.
# 1. Restore baseline
tar -xzvf /backups/backup_level0.tar.gz -C /restore --listed-incremental=/dev/null
# 2. Apply incrementals chronologically
tar -xzvf /backups/backup_inc_2023-10-01.tar.gz -C /restore --listed-incremental=/dev/null
tar -xzvf /backups/backup_inc_2023-10-02.tar.gz -C /restore --listed-incremental=/dev/null
Note: Use --listed-incremental=/dev/null during extraction to prevent tar from trying to update a local snapshot file.
Remote Backups via SSH
tar streams effortlessly over SSH, allowing "push" or "pull" backups without intermediate local storage Not complicated — just consistent. Turns out it matters..
Push Local Directory to Remote Server
tar -czf - /home/user/data | ssh user@backup-server "cat > /remote/path/data_backup.tar.gz"
Pull Remote Directory to Local Machine
ssh user@remote-server "tar -czf - /var/www" | tar -xzvf - -C /local/backup
This extracts directly to your local disk, preserving permissions (-p is default for root) and directory structure.
Verification and Integrity Checks
Never trust a backup you haven't tested And that's really what it comes down to..
1. List Contents (Dry Run)
Verify the archive structure and permissions without writing to disk:
tar -tzvf system_backup.tar.gz | head -20
-t/--list: Table of contents.- Check for unexpected absolute paths or missing directories.
2. Compare Archive to Filesystem (--diff / -d)
Detects discrepancies between the archive and the live source (modified files, permission drift, missing files):
tar -dzvf system_backup.tar.gz -C /
- Output shows only differences. Silent success means the archive matches the source perfectly.
- Critical: Run this before deleting source data or rotating media.
3. Checksum Validation
Generate a SHA256 hash immediately after creation and store it separately (e.g., in a .sha256 file or a database).
sha256sum system_backup.tar.gz > system_backup.tar.gz.sha256
Verify on the destination machine:
sha256sum -c system_backup.tar.gz.sha256
Automation: A strong Backup Script Template
Combine these concepts into a maintainable script (/usr/local/bin/backup.sh) That's the whole idea..
#!/bin/bash
set -euo pipefail
# --- Configuration ---
SOURCE_DIRS="/etc /home /var/www"
BACKUP_ROOT="/mnt/backup_nas"
EXCLUDE_FILE="/etc/backup_exclude.txt"
SNAPSHOT_FILE="${BACKUP_ROOT}/backup.snar"
RETENTION_DAYS=30
DATE=$(date +%F_%H-%M)
ARCHIVE_NAME="system_backup_${DATE}.tar.gz"
LOG_FILE="/var/log/backup.log"
# --- Pre-flight Checks ---
if [[ ! -f "$EXCLUDE_FILE" ]]; then
echo "Exclude file missing:
`$EXCLUDE_FILE"
exit 1
fi
if [[ ! -d "$BACKUP_ROOT" ]]; then
echo "Backup destination missing: $BACKUP_ROOT"
exit 1
fi
# --- Execution ---
echo "[$(date)] Starting backup: $ARCHIVE_NAME" | tee -a "$LOG_FILE"
# Create archive (Level 0 if snapshot missing, else Incremental)
tar -czpf "${BACKUP_ROOT}/${ARCHIVE_NAME}" \
--listed-incremental="${SNAPSHOT_FILE}" \
--exclude-from="${EXCLUDE_FILE}" \
--one-file-system \
--acls --xattrs \
${SOURCE_DIRS} 2>>"$LOG_FILE"
TAR_EXIT=${PIPESTATUS[0]}
# --- Post-Backup Verification ---
if [[ $TAR_EXIT -eq 0 ]]; then
echo "[$(date)] Archive created. Verifying integrity..." | tee -a "$LOG_FILE"
# 1. Checksum
sha256sum "${BACKUP_ROOT}/${ARCHIVE_NAME}" > "${BACKUP_ROOT}/${ARCHIVE_NAME}.sha256"
# 2. Quick Diff Check (Sample 50 random files to save time on large sets)
# Note: Full diff (-d) is ideal but slow; sampling balances speed/safety.
tar -tzf "${BACKUP_ROOT}/${ARCHIVE_NAME}" | shuf -n 50 | \
tar -dzf "${BACKUP_ROOT}/${ARCHIVE_NAME}" -C / -T - 2>>"$LOG_FILE"
echo "[$(date)] Backup successful: ${ARCHIVE_NAME}" | tee -a "$LOG_FILE"
else
echo "[$(date)] ERROR: tar exited with code $TAR_EXIT" | tee -a "$LOG_FILE"
exit 1
fi
# --- Retention Policy ---
echo "[$(date)] Applying retention policy (${RETENTION_DAYS} days)..." | tee -a "$LOG_FILE"
find "$BACKUP_ROOT" -name "system_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
find "$BACKUP_ROOT" -name "system_backup_*.tar.gz.sha256" -mtime +$RETENTION_DAYS -delete
# Snapshot file rotation: Keep snapshot to allow incrementals, but reset monthly
# to prevent snapshot corruption drift over very long periods.
if [[ $(date +%d) == "01" ]]; then
mv "${SNAPSHOT_FILE}" "${SNAPSHOT_FILE}.$(date -d 'last month' +%Y%m)"
echo "[$(date)] Monthly snapshot rotation performed." | tee -a "$LOG_FILE"
fi
echo "[$(date)] Backup job finished." | tee -a "$LOG_FILE"
Script Highlights:
set -euo pipefail: Ensures the script aborts on errors, unset variables, or pipeline failures.${PIPESTATUS[0]}: Capturestar's specific exit code even when piped totee.--one-file-system: Prevents traversing into mounted network shares,/proc,/sys, or separate partitions (like/homeon a different drive) unless explicitly listed inSOURCE_DIRS.- Sampled Verification (
shuf -n 50): A pragmatic compromise; a fulltar -don terabytes takes hours. Sampling 50 random files catches corruption/media errors quickly. - Snapshot Rotation: Incremental snapshots (
backup.snar) grow indefinitely and can become corrupted. Resetting them monthly (forcing a Level 0) guarantees a clean chain.
Restoration: The Only Metric That Matters
A backup strategy is defined not by how well it backs up, but by how reliably it restores. Practice these scenarios quarterly.
Scenario 1: Single File Recovery (User Error)
# Extract single file to stdout, pipe to destination
tar -xzf /backups/system_backup_2023-10-15.tar.gz -O etc/nginx/nginx.conf > /tmp/nginx.conf.restored
# Verify diff
diff -u /etc/nginx/nginx.conf /tmp/nginx.conf.restored
Scenario 2: Full System Bare-Metal Recovery
-
Boot target machine via Live USB (match distro/arch: Ubuntu 22.04 Live for Ubuntu 22.04 restore) Most people skip this — try not to..
-
Partition/Format disks (
lsblk,mkfs.ext4,mkswap). -
Mount root partition
-
Mount root partition to
/mnt, then recreate the directory skeleton (mkdir -p /mnt/{proc,sys,dev,boot,home,var,tmp}) Worth keeping that in mind.. -
Extract the most recent full backup into the mounted filesystem:
# Identify latest Level 0 backup LATEST=$(ls -1t /backups/system_backup_*.tar.gz | head -n1) tar -xzpf "$LATEST" -C /mnt --xattrs --acls --numeric-owner -
Overlay subsequent incremental backups in chronological order (tar snapshot replays the deltas):
for inc in $(ls -1t /backups/system_backup_*.tar.gz | tail -r); do tar -xzpf "$inc" -C /mnt --xattrs --acls --numeric-owner --keep-old-files=false done -
Recreate missing device nodes and rebind virtual filesystems before chroot:
for d in dev proc sys; do mount --bind /$d /mnt/$d; done -
chrootin, regenerate the bootloader and initramfs, and fixfstabUUIDs if the disk layout changed:chroot /mnt /bin/bash blkid > /tmp/uuids # reconcile against /etc/fstab grub-install /dev/sda && update-grub update-initramfs -u -k all exit -
Unmount cleanly and reboot. Verify
systemctl --failedis empty on first boot.
Critical detail: Always use
--numeric-ownerduring restore. A Live USB environment maps UIDs/GIDs arbitrarily, and omitting this flag will silently chown system files to the wrong owners, breaking services in ways that are brutal to diagnose post-boot Nothing fancy..
Scenario 3: Verifying Integrity Before You Trust It
Before any restore, confirm the archive hasn't silently rotted on disk:
# Recompute and compare the stored checksum
sha256sum -c /backups/system_backup_2023-10-15.tar.gz.sha256
If the checksum fails, stop. Do not restore from a known-corrupt archive hoping for the best — fall back to the previous backup in the chain.
Operational Hardening
A working script is only half the job. The following practices separate a backup that runs from one that actually saves you:
- Test the tail, not just the head. Restoration drills must include your oldest retained backup, not only yesterday's. Silent bit-rot tends to surface in cold storage.
- Offsite copy. The script above writes to local disk, which protects against deletion and corruption but not against fire, theft, or a dead controller. Replicate
BACKUP_ROOTto object storage or a remote host:rclone sync "$BACKUP_ROOT" remote:s3-bucket --checksum --transfers 4 - Alert on silence, not just failure. A cron job that dies before logging anything looks identical to a quiet success. A dead-man's-switch check (
healthchecks.ioor similar) that pages you when the backup does not check in closes that gap. - Encrypt at rest. If backups leave the machine, wrap the transfer with
ageorgpgso a compromised bucket doesn't hand an attacker your entire filesystem. - Log rotation. The
LOG_FILEgrows unbounded across runs. Add alogrotatestanza so logs don't eventually fill the very disk you're trying to protect.
Conclusion
Reliable backups are less a script than a discipline. Here's the thing — the tar-plus-snapshot approach laid out here is deliberately boring: it uses a ubiquitous tool, avoids fragile dependencies, samples for corruption instead of assuming success, and rotates its incremental chain before drift accumulates. That predictability is the point Most people skip this — try not to..
But none of it counts until you've restored from it. The scenarios above — single file, bare-metal, and integrity verification — should be rehearsed on a schedule, with the oldest backup in your retention window, because that is the one you'll actually need during a real disaster. Pair the local archive with an offsite encrypted copy, alert on missing check-ins rather than reported errors, and confirm checksums before trusting any restore.
Do that, and your backup stops being a hopeful ritual that runs in the background and becomes what it was always meant to be: a tested guarantee that you can get back to work Easy to understand, harder to ignore..