remove-small-dirs 999 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env bash
  2. # Remove directories below a specified size (in KB)
  3. # Usage: remove-small-dirs DIRECTORY [SIZE_THRESHOLD]
  4. # Default SIZE_THRESHOLD is 1000 KB
  5. set -euo pipefail
  6. if [[ $# -lt 1 ]]; then
  7. echo "You must provide a directory." >&2
  8. exit 1
  9. fi
  10. dir="$1"
  11. SIZE="${2:-1000}"
  12. if [[ ! -d "$dir" ]]; then
  13. echo "Directory does not exist: $dir" >&2
  14. exit 1
  15. fi
  16. # Find directories with size less or equal to SIZE
  17. small_dirs=$(find "$dir" -mindepth 1 -type d -exec du -ks {} + | awk -v size="$SIZE" '$1 <= size {print $2}')
  18. if [[ -z "$small_dirs" ]]; then
  19. echo "No directories with size <= $SIZE KB found in $dir."
  20. exit 0
  21. fi
  22. echo "Directories to be removed:"
  23. echo "$small_dirs"
  24. read -r -p "Is this OK? [y/N] " response
  25. response="${response,,}" # Convert to lowercase
  26. if [[ ! "$response" =~ ^(yes|y)$ ]]; then
  27. echo "Exiting, no changes were made."
  28. exit 0
  29. fi
  30. echo "$small_dirs" | xargs -d'\n' rm -rf
  31. echo "Removed the following directories:"
  32. echo "$small_dirs"