Skip to content

Instantly share code, notes, and snippets.

@Dissimilis
Last active July 3, 2023 11:22
Show Gist options
  • Save Dissimilis/94beeade84baa5a533206ce7af2d52aa to your computer and use it in GitHub Desktop.
Save Dissimilis/94beeade84baa5a533206ce7af2d52aa to your computer and use it in GitHub Desktop.
Bash script to backup directory while keeping only X backups
#!/bin/bash
# Check if the input directory, output directory, and filename prefix are provided
if [ "$#" -ne 4 ]; then
echo "Makes backup of <input_directory> keeping last <retention> number of backups in <output directory>"
echo "Usage: $0 <input_directory> <output_directory> <filename_prefix> <retention>"
exit 1
fi
input_dir="$1"
output_dir="$2"
filename_prefix="$3"
max_backups="$4"
# Generate the date and time prefix
date_time_prefix=$(date +%Y%m%d_%H%M%S)
# File to store the last used backup ID
last_id_file="${output_dir}/last_id.txt"
# Check if the last ID file exists
if [ -f "$last_id_file" ]; then
# Read the last used ID from the file
last_id=$(cat "$last_id_file")
else
# If the file doesn't exist, start with ID 1
last_id=0
fi
# Increment the ID
backup_id=$((last_id + 1))
# Update the last ID file with the new ID
echo "$backup_id" > "$last_id_file"
# Create the backup directory if it doesn't exist
mkdir -p "$output_dir"
# Create the tar backup, ignoring failed reads
tar --use-compress-program=zstdmt -cf "${output_dir}/${date_time_prefix}_${filename_prefix}_${backup_id}.tar.zst" --ignore-failed-read "$input_dir"
# Set the exit code to 0
exit_code=0
# Print the backup ID
echo "Backup created: ${date_time_prefix}_${filename_prefix}_${backup_id}"
# Delete old backups if there are more than the maximum number of backups
backup_files=("${output_dir}/"*.tar.zst)
num_backups=${#backup_files[@]}
if [ "$num_backups" -gt "$max_backups" ]; then
num_to_delete=$((num_backups - max_backups))
for (( i=0; i < num_to_delete; i++ )); do
rm "${backup_files[$i]}"
echo "Deleted backup: ${backup_files[$i]}"
done
fi
# Exit with the tar command's exit code
exit "$exit_code"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment