WEBTOOLIST.
STATIC WEB PLATFORM
NO ACCOUNTS / NOTHING TO INSTALL

$ webtoolist --script backup-directory-tar

Timestamped Directory Backup

Create a compressed, timestamped tar archive of a directory and verify it.

category Backup and Recovery shell Bash 4+ updated 2026-09-24
backuptararchiveverify
Safety notes
  • Writes an archive to disk; check free space for large trees.
  • The archive is not encrypted. Use age or gpg if the data is sensitive.

Dependencies: tar, sha256sum

Usage

  • Pass the directory to back up and the destination directory.
  • The script refuses to write the archive inside the source tree.

Script

#!/usr/bin/env bash
set -euo pipefail

src="${1:-}"
out_dir="${2:-}"
[[ -n "$src" && -d "$src" ]] || { echo "usage: $0 SRC_DIR OUT_DIR" >&2; exit 1; }
[[ -n "$out_dir" ]] || { echo "usage: $0 SRC_DIR OUT_DIR" >&2; exit 1; }

src_abs="$(cd "$src" && pwd -P)"
mkdir -p "$out_dir"
out_abs="$(cd "$out_dir" && pwd -P)"

case "$out_abs/" in
  "$src_abs"/*) echo "refusing to write inside the source tree" >&2; exit 1 ;;
esac

stamp="$(date +%Y%m%d-%H%M%S)"
name="$(basename "$src_abs")-$stamp.tar.gz"
archive="$out_abs/$name"

tar -C "$(dirname "$src_abs")" -czf "$archive" "$(basename "$src_abs")"
sha256sum "$archive" > "$archive.sha256"

if tar -tzf "$archive" >/dev/null; then
  echo "created: $archive"
  echo "checksum: $archive.sha256"
  echo "size: $(du -h "$archive" | cut -f1)"
else
  echo "archive verification failed" >&2
  exit 1
fi

Example

./backup-directory-tar ~/projects /mnt/backups
sha256sum -c /mnt/backups/projects-*.tar.gz.sha256

Notes

  • Listing the archive is a quick integrity check, not a restore test. Periodically restore a sample.
  • Keep at least one backup off the machine that holds the source data.

Related scripts

Verify a Tar Backup

Check an archive's checksum, list its contents, and compare a sample safely.

Backup and Recovery

Rsync Snapshot Backup

Mirror a directory to a backup target with dry-run, delete protection, and a log.

Backup and Recovery

Safe SQLite Backup

Use SQLite's online backup API to copy a live database consistently.

Backup and Recovery

Archive Old Files

Move files untouched for N days into a dated archive directory.

File Management