s4ros icon

delete_old_backups

s4ros | PRO | 12/04/20 11:36:14 AM UTC (Edited) | 0 ⭐ | 2681 👁️ | Never ⏰ | []
Bash |

620 B

|

None

|

0 👍

/

0 👎

#!/bin/bash
 
### Usage message
if [[ -z $1 ]]; then
    cat <<- EOT
Usage: $0 <PATH_TO_DIR_WITH_BACKUPS> [RETENTION]
 
PATH_TO_DIR_WITH_BACKUPS - self explainatory, eg. /opt/backups
 
RETENTION - number of last backups to leave (based on modification time)
 
EOT
    exit 1
fi
 
 
# will leave last N files untouched
RETENTION=${2:-5}
 
BASEDIR=$(dirname $0)
BACKUP_DIR=$1
FILES_LIST=( $(ls -1trh ${BACKUP_DIR}/*.sql.bz2) )
ARR_SIZE=${#FILES_LIST[@]}
 
if [[ ${ARR_SIZE} -gt ${RETENTION} ]]; then
    LEAVE_END_IDX=$((ARR_SIZE - RETENTION))
    LEAVE=${FILES_LIST[@]:0:${LEAVE_END_IDX}}
 
    rm ${LEAVE[@]}
fi

Comments