Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # --- Configuration ---
- # List of directories to search. Add more if you like.
- # BE CAREFUL adding broad paths like "/" as it can be slow and risky.
- SEARCH_PATHS=(
- "/tmp"
- "/var/tmp"
- "$HOME/.cache"
- )
- # Find files older than this many days (based on last access time).
- DAYS_OLD=15
- # --- End of Configuration ---
- # Inform the user what's happening
- echo "🔍 Searching for temporary and unused files in the following locations:"
- for path in "${SEARCH_PATHS[@]}"; do
- echo " - $path"
- done
- echo "Looking for files not accessed in the last $DAYS_OLD days..."
- echo "---------------------------------------------------"
- # Create a temporary file to store the list of files to be deleted
- FILE_LIST=$(mktemp)
- # Find files and write the list to the temporary file.
- # -type f: Only find files.
- # -atime +$DAYS_OLD: Find files not accessed for more than DAYS_OLD days.
- # -print0: Use a null character to separate filenames, which safely handles spaces.
- find "${SEARCH_PATHS[@]}" -type f -atime "+$DAYS_OLD" -print0 > "$FILE_LIST"
- # Check if the file list is empty
- if ! [ -s "$FILE_LIST" ]; then
- echo "✅ No temporary files found matching the criteria. Your system is clean!"
- rm "$FILE_LIST"
- exit 0
- fi
- # --- Generate Report ---
- echo "📄 Report: The following files were found:"
- # Read from the null-terminated file list and display details
- xargs -0 ls -lh < "$FILE_LIST"
- echo "---------------------------------------------------"
- # Calculate the total size of the found files
- TOTAL_SIZE=$(xargs -0 du -ch < "$FILE_LIST" | grep total$ | awk '{print $1}')
- FILE_COUNT=$(xargs -0 -n1 < "$FILE_LIST" | wc -l)
- echo "📊 Summary:"
- echo " - Total files found: $FILE_COUNT"
- echo " - Total size: $TOTAL_SIZE"
- echo ""
- # --- Ask for Confirmation ---
- read -p "❓ Do you want to delete all these files? (y/n): " CONFIRM
- if [[ "$CONFIRM" =~ ^[Yy]$ ]]; then
- echo "🗑️ Deleting files..."
- # Safely delete the files using the null-terminated list
- xargs -0 rm -f < "$FILE_LIST"
- echo "✅ Done. All listed files have been deleted."
- else
- echo "👍 Aborted. No files were deleted."
- fi
- # --- Cleanup ---
- # Remove the temporary file that stored the list
- rm "$FILE_LIST"
- echo "✨ Script finished."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement