s4ros

delete_old_backups

Oct 31st, 2020
1,043
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. ### Usage message
  4. if [[ -z $1 ]]; then
  5.     cat <<- EOT
  6. Usage: $0 <PATH_TO_DIR_WITH_BACKUPS> [RETENTION]
  7.  
  8. PATH_TO_DIR_WITH_BACKUPS - self explainatory, eg. /opt/backups
  9.  
  10. RETENTION - number of last backups to leave (based on modification time)
  11.  
  12. EOT
  13.     exit 1
  14. fi
  15.  
  16.  
  17. # will leave last N files untouched
  18. RETENTION=${2:-5}
  19.  
  20. BASEDIR=$(dirname $0)
  21. BACKUP_DIR=$1
  22. FILES_LIST=( $(ls -1trh ${BACKUP_DIR}/*.sql.bz2) )
  23. ARR_SIZE=${#FILES_LIST[@]}
  24.  
  25. if [[ ${ARR_SIZE} -gt ${RETENTION} ]]; then
  26.     LEAVE_END_IDX=$((ARR_SIZE - RETENTION))
  27.     LEAVE=${FILES_LIST[@]:0:${LEAVE_END_IDX}}
  28.  
  29.     rm ${LEAVE[@]}
  30. fi
RAW Paste Data