Advertisement
llsumitll

bash

Jun 22nd, 2025
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.26 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # --- Configuration ---
  4. # List of directories to search. Add more if you like.
  5. # BE CAREFUL adding broad paths like "/" as it can be slow and risky.
  6. SEARCH_PATHS=(
  7.     "/tmp"
  8.     "/var/tmp"
  9.     "$HOME/.cache"
  10. )
  11.  
  12. # Find files older than this many days (based on last access time).
  13. DAYS_OLD=15
  14.  
  15. # --- End of Configuration ---
  16.  
  17. # Inform the user what's happening
  18. echo "🔍 Searching for temporary and unused files in the following locations:"
  19. for path in "${SEARCH_PATHS[@]}"; do
  20.     echo "   - $path"
  21. done
  22. echo "Looking for files not accessed in the last $DAYS_OLD days..."
  23. echo "---------------------------------------------------"
  24.  
  25. # Create a temporary file to store the list of files to be deleted
  26. FILE_LIST=$(mktemp)
  27.  
  28. # Find files and write the list to the temporary file.
  29. # -type f: Only find files.
  30. # -atime +$DAYS_OLD: Find files not accessed for more than DAYS_OLD days.
  31. # -print0: Use a null character to separate filenames, which safely handles spaces.
  32. find "${SEARCH_PATHS[@]}" -type f -atime "+$DAYS_OLD" -print0 > "$FILE_LIST"
  33.  
  34. # Check if the file list is empty
  35. if ! [ -s "$FILE_LIST" ]; then
  36.     echo "✅ No temporary files found matching the criteria. Your system is clean!"
  37.     rm "$FILE_LIST"
  38.     exit 0
  39. fi
  40.  
  41. # --- Generate Report ---
  42. echo "📄 Report: The following files were found:"
  43. # Read from the null-terminated file list and display details
  44. xargs -0 ls -lh < "$FILE_LIST"
  45. echo "---------------------------------------------------"
  46.  
  47. # Calculate the total size of the found files
  48. TOTAL_SIZE=$(xargs -0 du -ch < "$FILE_LIST" | grep total$ | awk '{print $1}')
  49. FILE_COUNT=$(xargs -0 -n1 < "$FILE_LIST" | wc -l)
  50.  
  51. echo "📊 Summary:"
  52. echo "   - Total files found: $FILE_COUNT"
  53. echo "   - Total size: $TOTAL_SIZE"
  54. echo ""
  55.  
  56. # --- Ask for Confirmation ---
  57. read -p "❓ Do you want to delete all these files? (y/n): " CONFIRM
  58.  
  59. if [[ "$CONFIRM" =~ ^[Yy]$ ]]; then
  60.     echo "🗑️ Deleting files..."
  61.     # Safely delete the files using the null-terminated list
  62.     xargs -0 rm -f < "$FILE_LIST"
  63.     echo "✅ Done. All listed files have been deleted."
  64. else
  65.     echo "👍 Aborted. No files were deleted."
  66. fi
  67.  
  68. # --- Cleanup ---
  69. # Remove the temporary file that stored the list
  70. rm "$FILE_LIST"
  71.  
  72. echo "✨ Script finished."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement