Rsync Backup – How to Keep Only 10 Backup Folders

rsync

TL;DR

Only keep latest 10 backup folders via rsync


I am using rsync to backup my files onto a remote server OR another directory on the same machine as such:

SRC="${1}"
DEST="${2}"
PREFIX="$( date '+%Y-%m-%d__%H_%M_%S' )"

rsync --archive \
    --progress \
    --compress \
    --delete \
    --delete-excluded \
    --link-dest=../current \
    --delay-updates \
    --partial-dir=".partial-${PREFIX}" \
    "${SRC}" "${DEST}/${PREFIX}"

With this I will have the following directory structure after a few backups

$ ls ${DEST}/
2017-02-26__16_36_19/
2017-02-26__16_41_23/
2017-02-26__16_41_24/
2017-02-26__16_41_25/
current -> 2017-02-26__16_41_25/

current always points to the latest backup that has been done.

Now as I don't know if $DEST is either a local folder OR a remote server address, I would like to use rsync to always delete all other folders inside $DEST which are not the latest 10. So basically I just want to keep the latest 10 backup folders and remove the rest.

Is this somehow possible even though I don't know if the rsync script is triggered for a directory on the same machine or an ssh server address?

Best Answer

rsync has not such option ("delete all dirs older than..."), you had to achieve the same effect by using ssh and a custom script.

Even better, you can use rsnapshot to manage backup rotation and retention.