add cleanup for backups

This commit is contained in:
adam committed 2026-01-12 14:59:46 +00:00
1 parent f53ffba649
commit 753060563f
1 file changed
+23 -3
+23 -3
View File
@@ -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 <<EOF
Usage: ${0##*/} [-l vm[,vm...]] [-d backup_dir] [-t lxc|incus] [-h]
Usage: ${0##*/} [-l vm[,vm...]] [-d backup_dir] [-t lxc|incus] [-c <keep n backups>] [-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 "$@"