prunefiles 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env bash
  2. #
  3. # prunefiles, a function to remove all but the n latest versions of a file
  4. # by Bryan Roessler
  5. #
  6. # This file can be sourced directly to import `prunefiles` or run as a script
  7. #
  8. # Useful to prune rpm repositories of obsolete packages
  9. #
  10. declare -a _filePrefixes
  11. prunefiles () {
  12. #############
  13. # DEFAULTS ##
  14. #############
  15. # Default number of matching files to keep
  16. _keepInt=1
  17. #############
  18. # FUNCTIONS #
  19. #############
  20. _printHelpAndExit () {
  21. cat <<-'EOF'
  22. USAGE:
  23. pruneFiles -k 3 thisfileprefix [thatfileprefix]
  24. OPTIONS
  25. -k|--keep NUMBER
  26. Keep NUMBER of latest files that matches each file prefix (Default: 1)
  27. EOF
  28. # Exit using passed exit code
  29. [[ -z $1 ]] && exit 0 || exit "$1"
  30. }
  31. _parseInput () {
  32. if _input=$(getopt -o +k: -l keep: -- "$@"); then
  33. eval set -- "$_input"
  34. while true; do
  35. case "$1" in
  36. -k|--keep)
  37. shift && _keepInt=$1
  38. ;;
  39. --)
  40. shift && break
  41. ;;
  42. esac
  43. shift
  44. done
  45. else
  46. echo "Incorrect option(s) provided"
  47. _printHelpAndExit 1
  48. fi
  49. _filePrefixes=( "$@" )
  50. }
  51. _findAndRemove () {
  52. for _filePrefix in "${_filePrefixes[@]}"; do
  53. for _file in $(find . -maxdepth 1 -type f -name "${_filePrefix}*" -printf '%T@ %p\n' | sort -r -z -n | tail -n+$(($_keepInt + 1)) | awk '{ print $2; }'); do
  54. rm "$_file"
  55. done
  56. done
  57. }
  58. __main () {
  59. _parseInput "$@"
  60. _findAndRemove
  61. }
  62. __main "$@"
  63. }
  64. # Allow script to be safely sourced
  65. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  66. prunefiles "$@"
  67. exit $?
  68. fi