prunefiles 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env bash
  2. # Remove all but the latest N versions of files matching given prefixes
  3. # See prunefiles --help for usage
  4. prunefiles() {
  5. declare -ag PREFIXES
  6. declare -g KEEP_INT=1 # default number of files to keep
  7. printHelpAndExit() {
  8. cat <<-'EOF'
  9. USAGE:
  10. prunefiles -k 3 thisfileprefix [thatfileprefix]
  11. OPTIONS:
  12. -k, --keep NUMBER
  13. Keep NUMBER of the latest files that match each file prefix (Default: 1)
  14. -h, --help
  15. Print this help dialog and exit
  16. EOF
  17. [[ -z "$1" ]] && exit 0 || exit "$1"
  18. }
  19. parseInput() {
  20. if _input=$(getopt -o hk: -l help,keep: -- "$@"); then
  21. eval set -- "$_input"
  22. while true; do
  23. case "$1" in
  24. -k|--keep) shift; KEEP_INT="$1" ;;
  25. -h|--help) printHelpAndExit 0 ;;
  26. --) shift; break ;;
  27. esac
  28. shift
  29. done
  30. else
  31. echo "Incorrect option(s) provided"
  32. printHelpAndExit 1
  33. fi
  34. PREFIXES=("$@")
  35. }
  36. findAndRemove() {
  37. local prefix file
  38. for prefix in "${PREFIXES[@]}"; do
  39. # List files matching the prefix sorted by modification time (latest first),
  40. # then remove all except the first KEEP_INT files.
  41. while IFS= read -r file; do
  42. echo "Removing: $file"
  43. rm -- "$file"
  44. done < <(
  45. find . -maxdepth 1 -type f -name "${prefix}*" -printf '%T@ %p\n' | \
  46. sort -rn | \
  47. awk -v keep="$KEEP_INT" 'NR > keep {print $2}'
  48. )
  49. done
  50. }
  51. main() {
  52. parseInput "$@"
  53. findAndRemove
  54. }
  55. main "$@"
  56. }
  57. # Allow script to be safely sourced
  58. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  59. prunefiles "$@"
  60. exit $?
  61. fi