From 753060563f3336c91f0e31460dfb609f37fcd6aa Mon Sep 17 00:00:00 2001 From: adam Date: Mon, 12 Jan 2026 14:59:46 +0000 Subject: [PATCH] add cleanup for backups --- lxc-backup.sh | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/lxc-backup.sh b/lxc-backup.sh index dc5bd9c..126290d 100755 --- a/lxc-backup.sh +++ b/lxc-backup.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash main() { - while getopts ":l:d:t:" opt; do + while getopts ":l:d:t:c:h" opt; do case "${opt}" in l) unset VM_FILTER @@ -14,6 +14,10 @@ main() { t) declare -g TARGET="$OPTARG" ;; + c) + declare -g run_cleanup=y + declare -g files_to_keep="${OPTARG}" + ;; h) usage ;; @@ -43,12 +47,13 @@ list_vms() { usage() { cat <] [-h] Options: -l Comma-separated list of VMs to back up -d Directory where backups will be stored (default: current directory) -t Manager type: lxc or incus (default: lxc) + -c Cleanup old backups keeping a set number (default: 2) -h Show this message EOF @@ -80,7 +85,22 @@ start_backup() { [[ -d "$destination" ]] || mkdir "$destination" [[ -f "${destination}/${backup_name}" ]] && { echo "Backup already exists"; return 2; } - lxc export "$vm" "${destination}/${backup_name}" + lxc export "$vm" "${destination}/${backup_name}" || { echo "Error exporting $vm"; return 1; } + + [[ -n "$run_cleanup" ]] && prune_backups "$destination" +} + +prune_backups() { + local backup_directory="$1" + mapfile -t backup_files < <(find "$backup_directory" -maxdepth 1 -name "*.tar.gz" -printf '%T@ %p\n' | sort -n | head -n "-${files_to_keep}" | cut -d' ' -f2-) + + if [[ ${#backup_files[@]} -gt 0 ]]; then + echo "Removing ${#qcow2_files[@]} old backup files for $vm (keeping last $total_files_to_keep files)" + printf '%s\0' "${backup_files[@]}" | xargs -0 rm -fv + else + echo "No old backups to remove for $vm" + fi + } main "$@"