prunefiles 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. EOF
  15. # Exit using passed exit code
  16. [[ -z $1 ]] && exit 0 || exit "$1"
  17. }
  18. parseInput () {
  19. if _input=$(getopt -o +k: -l keep: -- "$@"); then
  20. eval set -- "$_input"
  21. while true; do
  22. case "$1" in
  23. -k|--keep)
  24. shift && KEEP_INT=$1
  25. ;;
  26. -h|--help)
  27. printHelpAndExit 0
  28. ;;
  29. --)
  30. shift; break
  31. ;;
  32. esac
  33. shift
  34. done
  35. else
  36. echo "Incorrect option(s) provided"
  37. printHelpAndExit 1
  38. fi
  39. PREFIXES=( "$@" )
  40. }
  41. findAndRemove () {
  42. declare prefix file
  43. for prefix in "${PREFIXES[@]}"; do
  44. 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
  45. rm "$file"
  46. done
  47. done
  48. }
  49. main () {
  50. parseInput "$@"
  51. findAndRemove
  52. }
  53. main "$@"
  54. }
  55. # Allow script to be safely sourced
  56. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  57. prunefiles "$@"
  58. exit $?
  59. fi