Keep only a certain amount of backups (tarballs) in a directory

If you have zsh available, you could use it to supplement your bash script:

# ...
tar -cpzf "$DESDIR"/"$FILENAME" "$SRCDIR" 
zsh -c 'rm -- "$DESDIR"/backup-*-tar.gz(om[11,-1])'

The meaning here is to ask zsh to call rm with a list of files; that list of files is generated from the wildcard $DESDIR/backup-*-tar.gz (which I gathered from your script -- and added quoting to), followed by a zsh "glob qualifier", in parenthesis. That glob qualifier says to "order" (sort) the matching files by modification time (newest first); that list is then sliced to select only the 11th and onwards files -- which are then removed, leaving the 10 newest files. The -1 syntax means "count backwards from the end of the list" and effectively refers to the last element of the list.


Add the following in the script towards the end:

find "$DESDIR/$FILENAME" -type f -mtime +10 -delete

This will find your backup file (tar.gz) in the directory and delete any backup that is more than 10 days older.