Skip to content

Instantly share code, notes, and snippets.

@bendem
Created March 21, 2025 15:07
Show Gist options
  • Save bendem/578b8fd9171c330b0390c248ec5d50e5 to your computer and use it in GitHub Desktop.
Save bendem/578b8fd9171c330b0390c248ec5d50e5 to your computer and use it in GitHub Desktop.
rotate files, keeping the last x
# bad, if the recent backups failed, this can end up removing everything
find . -type f -name 'test-*' -mtime +5 -delete
# good, keeps 5 files at all time
keep=5
find . -type f -name 'test-*' -printf '%T@\0%p\n' \
| sort -rn \
| cut -d $'\0' -f2 \
| tail -n +$(( keep + 1 ) \
| xargs rm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment