Clean backups older than retention time

Command can use default retention time or the one passed as argument.
This commit is contained in:
Jeremy Gardais 2021-04-12 19:06:47 +02:00
parent de9548d9e9
commit 1ebd39d86a
Signed by: jegardai
GPG Key ID: E759BAA22501AF32
1 changed files with 33 additions and 2 deletions

View File

@ -1,7 +1,10 @@
#!/bin/sh
# This script will backup /etc/pve content :
# 1. Make a tar to /etc/proxmox.pve/backup/
# 1. Make an archive to a first directory (default: /etc/proxmox.pve/backup/).
# 2. Hard link a fix archive name (pve.latest.tar.gz) to new archive
# Easy to monitor (this path can be expected).
# 3. Clean backups older than retention time (default: 7).
# This script can be call by a cronjob (eg. daily).
@ -14,6 +17,7 @@ readonly NBARGS="${#}"
readonly DEFAULT_LOCAL_BKP_DIR="/etc/proxmox.pve/backup"
readonly TODAY_VAR=$(date +%Y%m%d)
readonly DEFAULT_RETENTION_TIME="7"
## Colors
readonly PURPLE='\033[1;35m'
@ -25,7 +29,7 @@ readonly COLOR_DEBUG="${PURPLE}"
usage() { # {{{
cat <<- EOF
usage: $PROGNAME [-d|-h|-l]
usage: $PROGNAME [-d|-h|-l|-r]
Backup /etc/pve content
@ -33,6 +37,12 @@ EXAMPLES:
- Backup /etc/pve content to ${DEFAULT_LOCAL_BKP_DIR} directory
${PROGNAME}
- Backup /etc/pve content to /var/backups/pve directory
${PROGNAME} --local /var/backups/pve
- Backup to default path and keep backups for 14 days
${PROGNAME} --retention 14
OPTIONS:
-d,--debug
Enable debug messages.
@ -44,6 +54,10 @@ OPTIONS:
Path to a local directory to store backup and override
default path (${DEFAULT_LOCAL_BKP_DIR}).
-r,--retention,--retention-time
Backups older than retention time (default: ${DEFAULT_RETENTION_TIME})
will be delete.
EOF
}
@ -66,6 +80,12 @@ define_vars() { # {{{
local_bkp_dir="${DEFAULT_LOCAL_BKP_DIR}"
fi
## }}}
## If retention_time wasn't defined {{{
if [ -z "${retention_time}" ]; then
## Use default retention time to clean backups
retention_time="${DEFAULT_RETENTION_TIME}"
fi
## }}}
}
# }}}
@ -125,6 +145,11 @@ main() { # {{{
chown -R backup:adm -- "${local_bkp_dir}" \
&& chmod 'u+rwX,g+rX,o-rwx' -R -- "${local_bkp_dir}"
## }}}
## Clean files older than $retention_time {{{
### OR exit with error code 4 if it fails
find "${local_bkp_dir}" -maxdepth 1 -type f -mtime +"${retention_time}" -iname "pve.*.tar.gz" -delete \
|| exit 4
## }}}
}
# }}}
@ -165,6 +190,12 @@ if [ ! "${NBARGS}" -eq "0" ]; then
## Define local_bkp_dir
local_bkp_dir="${1}"
;;
-r|--retention,--retention-time ) ## clean backups older than retention time
## Move to the next argument
shift
## Define retention_time
retention_time="${1}"
;;
* ) ## unknow option
printf '%b\n' "${RED}Invalid option: ${1}${RESET}"
printf '%b\n' "---"