prunefiles 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env bash
  2. # prunefiles, a script/function to remove all but the n latest versions of a file
  3. #
  4. prunefiles () {
  5. declare -ag PREFIXES
  6. declare -g KEEP_INT=1 # default # 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 latest files that matches each file prefix (Default: 1)
  14. -h, --help
  15. Print this help dialog and exit
  16. EOF
  17. # Exit using passed exit code
  18. [[ -z $1 ]] && exit 0 || exit "$1"
  19. }
  20. parseInput () {
  21. if _input=$(getopt -o +hk: -l help,keep: -- "$@"); then
  22. eval set -- "$_input"
  23. while true; do
  24. case "$1" in
  25. -k|--keep)
  26. shift && KEEP_INT=$1
  27. ;;
  28. -h|--help)
  29. printHelpAndExit 0
  30. ;;
  31. --)
  32. shift; break
  33. ;;
  34. esac
  35. shift
  36. done
  37. else
  38. echo "Incorrect option(s) provided"
  39. printHelpAndExit 1
  40. fi
  41. PREFIXES=( "$@" )
  42. }
  43. findAndRemove () {
  44. declare prefix file
  45. for prefix in "${PREFIXES[@]}"; do
  46. for file in $(find . -maxdepth 1 -type f -name "${prefix}*" -printf '%T@ %p\n' | sort -r -z -n | tail -n+$((KEEP_INT + 1)) | awk '{ print $2; }'); do
  47. rm "$file"
  48. done
  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