Rotate backups with Bash script

Here is a simple script to rotate your backups:

#!/usr/bin/env bash


function number_of_backups() {
    echo `ls -1 $backup_location | wc -l`

function oldest_backup() {
    echo -n `ls -1 $backup_location | head -1`

while [ $(number_of_backups) -gt $max_number_of_backups ]
    rm -rf "$backup_location/$(oldest_backup)"

You should of course change backup_location and max_number_of_backups to fit you environment and needs.

2 Responses to Rotate backups with Bash script

  1. Your variable “$backup_location” in the “function oldest_backup” is not consistent with it being in all caps: $BACKUP_LOCATION

    If any one uses this script, please update line 11 with the case sensitive variable $backup_location.
    Replace $BACKUP_LOCATION with $backup_location


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>