Bash script to create differential tar.gz archives between two directories for lightweight, incremental versioning of new or modified files.
#!/bin/bash
# Script to create a differential archive between two directories
# Lightweight versioning: archives only new or modified files compared to the base
# Function to calculate SHA256 checksum of a file
file_checksum() {
sha256sum "$1" | awk '{print $1}'
}
# Parameter check
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <base_directory> <new_directory> <output_archive.tar.gz>"
exit 1
fi
base_dir="$1"
new_dir="$2"
output_archive="$3"
# Verify that directories exist
if [ ! -d "$base_dir" ]; then
echo "Error: base directory '$base_dir' not found." >&2
exit 2
fi
if [ ! -d "$new_dir" ]; then
echo "Error: new directory '$new_dir' not found." >&2
exit 3
fi
# Temporary file for list of modified or new files
tmp_file_list=$(mktemp)
# Loop over all files in the new directory
# find with -type f to consider only regular files
find "$new_dir" -type f | while read -r new_file; do
# Relative path of the file with respect to new_dir
rel_path="${new_file#$new_dir/}"
base_file="$base_dir/$rel_path"
if [ ! -f "$base_file" ]; then
# New file, add it
echo "$rel_path" >> "$tmp_file_list"
else
# File exists, compare checksum
checksum_new=$(file_checksum "$new_file")
checksum_base=$(file_checksum "$base_file")
if [ "$checksum_new" != "$checksum_base" ]; then
# Modified file
echo "$rel_path" >> "$tmp_file_list"
fi
fi
done
# If no modified or new files, notify and exit
if [ ! -s "$tmp_file_list" ]; then
echo "No new or modified files found. Archive not created."
rm "$tmp_file_list"
exit 0
fi
# Create tar.gz archive with the listed files
# -C new_dir to maintain relative structure
# --files-from reads the list of files to include
tar -czf "$output_archive" -C "$new_dir" --files-from="$tmp_file_list"
if [ $? -eq 0 ]; then
echo "Differential archive created successfully: $output_archive"
else
echo "Error during archive creation." >&2
fi
# Cleanup
rm "$tmp_file_list"
exit 0Hardware: No hardware components required.
Software: