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:

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}/
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?


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.

  • rdiff-backup is another popular alternative for rsync-like backups. – rvs Feb 26 '17 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.