Cache Management and Clearing on macOS
Manage and clear various types of cache across your MacFleet devices using command-line tools. This tutorial covers system cache, browser cache, application cache, and enterprise-wide cache management policies for optimal performance and storage management.
Understanding macOS Cache System
macOS maintains several types of cache to improve system and application performance:
Cache Types
- System Cache - Logs, diagnostic reports, temporary system files
- User Cache - Application-specific temporary files and data
- Browser Cache - Web browsing data, cookies, session storage
- Application Cache - App-specific cached data and preferences
- Font Cache - System and user font cache files
Cache Locations
- System:
/var/log/
,/Library/Caches/
,/System/Library/Caches/
- User:
~/Library/Caches/
,~/Library/Application Support/
- Browser: Browser-specific directories within user library
- Downloads:
~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV*
System Cache Management
Clear System Cache
#!/bin/bash
# Clear system-wide cache files
echo "🧹 Clearing system cache..."
# Clear system logs (with size limit for safety)
echo "Clearing system logs..."
sudo find /var/log -name "*.log" -type f -size +100M -delete 2>/dev/null
sudo find /var/log -name "*.out" -type f -size +50M -delete 2>/dev/null
# Clear system caches
echo "Clearing system caches..."
sudo rm -rf /Library/Caches/* 2>/dev/null
sudo rm -rf /System/Library/Caches/* 2>/dev/null
# Clear temporary files
echo "Clearing temporary files..."
sudo rm -rf /tmp/* 2>/dev/null
sudo rm -rf /var/tmp/* 2>/dev/null
echo "✅ System cache cleared successfully"
Clear User Cache
#!/bin/bash
# Clear current user's cache files
USER=$(whoami)
echo "🗂️ Clearing user cache for: $USER"
# Clear user caches
echo "Clearing user caches..."
rm -rf ~/Library/Caches/* 2>/dev/null
# Clear user logs
echo "Clearing user logs..."
rm -rf ~/Library/Logs/* 2>/dev/null
# Clear QuickLook thumbnails
echo "Clearing QuickLook thumbnails..."
rm -rf ~/Library/Caches/com.apple.QuickLook.thumbnailcache/* 2>/dev/null
# Clear Spotlight cache
echo "Clearing Spotlight cache..."
sudo mdutil -E / 2>/dev/null
echo "✅ User cache cleared successfully"
Browser Cache Management
Clear Safari Cache
#!/bin/bash
# Clear Safari browser cache
echo "🌐 Clearing Safari cache..."
# Check if Safari is running
if pgrep -x "Safari" > /dev/null; then
echo "⚠️ Safari is running. Please close Safari first."
read -p "Press Enter to continue after closing Safari..."
fi
# Clear Safari cache files
rm -rf ~/Library/Caches/com.apple.Safari/* 2>/dev/null
rm -rf ~/Library/Safari/LocalStorage/* 2>/dev/null
rm -rf ~/Library/Safari/Databases/* 2>/dev/null
rm -rf ~/Library/Safari/WebpageIcons.db 2>/dev/null
# Clear Safari downloads history
sqlite3 ~/Library/Safari/Downloads.plist "DELETE FROM Downloads;" 2>/dev/null
echo "✅ Safari cache cleared successfully"
Clear Chrome Cache
#!/bin/bash
# Clear Google Chrome browser cache
echo "🔍 Clearing Google Chrome cache..."
# Check if Chrome is installed
if [[ ! -d ~/Library/Application\ Support/Google/Chrome ]]; then
echo "ℹ️ Google Chrome not found on this system"
exit 0
fi
# Check if Chrome is running
if pgrep -x "Google Chrome" > /dev/null; then
echo "⚠️ Chrome is running. Please close Chrome first."
read -p "Press Enter to continue after closing Chrome..."
fi
# Clear Chrome cache files
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Cache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/GPUCache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/*.ldb 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/*.log 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Extension\ State/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Session\ Storage/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Current\ Session 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Storage/ext/* 2>/dev/null
echo "✅ Chrome cache cleared successfully"
Clear Firefox Cache
#!/bin/bash
# Clear Mozilla Firefox browser cache
echo "🦊 Clearing Firefox cache..."
# Check if Firefox is installed
if [[ ! -d ~/Library/Application\ Support/Firefox ]]; then
echo "ℹ️ Firefox not found on this system"
exit 0
fi
# Check if Firefox is running
if pgrep -x "firefox" > /dev/null; then
echo "⚠️ Firefox is running. Please close Firefox first."
read -p "Press Enter to continue after closing Firefox..."
fi
# Find Firefox profile directories
for profile in ~/Library/Application\ Support/Firefox/Profiles/*; do
if [[ -d "$profile" ]]; then
echo "Clearing Firefox profile: $(basename "$profile")"
rm -rf "$profile/cache2"/* 2>/dev/null
rm -rf "$profile/thumbnails"/* 2>/dev/null
rm -rf "$profile/cookies.sqlite-wal" 2>/dev/null
rm -rf "$profile/webappsstore.sqlite" 2>/dev/null
fi
done
echo "✅ Firefox cache cleared successfully"
Clear Opera Cache
#!/bin/bash
# Clear Opera browser cache
echo "🎭 Clearing Opera cache..."
# Check if Opera is installed
if [[ ! -d ~/Library/Application\ Support/com.operasoftware.Opera ]]; then
echo "ℹ️ Opera not found on this system"
exit 0
fi
# Check if Opera is running
if pgrep -x "Opera" > /dev/null; then
echo "⚠️ Opera is running. Please close Opera first."
read -p "Press Enter to continue after closing Opera..."
fi
# Clear Opera cache files
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/Cache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/GPUCache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/Session\ Storage/* 2>/dev/null
echo "✅ Opera cache cleared successfully"
Application Cache Management
Clear Application Caches
#!/bin/bash
# Clear application-specific caches
echo "📱 Clearing application caches..."
# Clear application caches in Containers
echo "Clearing containerized application caches..."
for container in ~/Library/Containers/*; do
if [[ -d "$container/Data/Library/Caches" ]]; then
app_name=$(basename "$container")
echo "Clearing cache for: $app_name"
rm -rf "$container/Data/Library/Caches"/* 2>/dev/null
fi
done
# Clear Adobe cache
if [[ -d ~/Library/Caches/Adobe ]]; then
echo "Clearing Adobe cache..."
rm -rf ~/Library/Caches/Adobe/* 2>/dev/null
fi
# Clear Microsoft Office cache
if [[ -d ~/Library/Caches/Microsoft ]]; then
echo "Clearing Microsoft Office cache..."
rm -rf ~/Library/Caches/Microsoft/* 2>/dev/null
fi
# Clear Xcode cache
if [[ -d ~/Library/Developer/Xcode/DerivedData ]]; then
echo "Clearing Xcode derived data..."
rm -rf ~/Library/Developer/Xcode/DerivedData/* 2>/dev/null
fi
echo "✅ Application caches cleared successfully"
Clear Download History
#!/bin/bash
# Clear download history and quarantine database
echo "📥 Clearing download history..."
# Clear quarantine events (download history)
sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* \
'DELETE FROM LSQuarantineEvent' 2>/dev/null
# Clear recent items
rm -rf ~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.RecentDocuments.sfl* 2>/dev/null
rm -rf ~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.RecentApplications.sfl* 2>/dev/null
echo "✅ Download history cleared successfully"
Clear Terminal History
#!/bin/bash
# Clear terminal command history
echo "💻 Clearing terminal history..."
# Clear bash history
rm -rf ~/.bash_sessions/* 2>/dev/null
rm -rf ~/.bash_history 2>/dev/null
# Clear zsh history
rm -rf ~/.zsh_sessions/* 2>/dev/null
rm -rf ~/.zsh_history 2>/dev/null
# Clear other shell histories
rm -rf ~/.history 2>/dev/null
rm -rf ~/.sh_history 2>/dev/null
echo "✅ Terminal history cleared successfully"
Enterprise Cache Management Script
#!/bin/bash
# MacFleet Cache Management Tool
# Comprehensive cache management for enterprise environments
# Configuration
LOG_FILE="/var/log/macfleet_cache.log"
BACKUP_DIR="/var/backups/macfleet/cache"
REPORT_DIR="/var/reports/macfleet/cache"
CONFIG_FILE="/etc/macfleet/cache_policy.conf"
# Cache policy settings
ENABLE_SYSTEM_CACHE_CLEAR=true
ENABLE_BROWSER_CACHE_CLEAR=true
ENABLE_APP_CACHE_CLEAR=true
ENABLE_DOWNLOAD_HISTORY_CLEAR=false
ENABLE_TERMINAL_HISTORY_CLEAR=false
CACHE_SIZE_THRESHOLD_MB=1000
CACHE_AGE_DAYS=30
# Logging function
log_action() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
# Setup directories
setup_directories() {
for dir in "$BACKUP_DIR" "$REPORT_DIR" "$(dirname "$CONFIG_FILE")"; do
if [[ ! -d "$dir" ]]; then
sudo mkdir -p "$dir"
log_action "Created directory: $dir"
fi
done
}
# Calculate cache size
calculate_cache_size() {
local path="$1"
if [[ -d "$path" ]]; then
du -sm "$path" 2>/dev/null | awk '{print $1}'
else
echo "0"
fi
}
# Generate cache report
generate_cache_report() {
local report_file="$REPORT_DIR/cache_report_$(date +%Y%m%d_%H%M%S).txt"
echo "📊 Generating cache analysis report..."
{
echo "MacFleet Cache Analysis Report"
echo "Generated: $(date)"
echo "Hostname: $(hostname)"
echo "User: $(whoami)"
echo "================================="
echo ""
echo "=== System Cache Analysis ==="
echo "System logs size: $(calculate_cache_size /var/log) MB"
echo "System cache size: $(calculate_cache_size /Library/Caches) MB"
echo "Temporary files size: $(calculate_cache_size /tmp) MB"
echo ""
echo "=== User Cache Analysis ==="
echo "User cache size: $(calculate_cache_size ~/Library/Caches) MB"
echo "User logs size: $(calculate_cache_size ~/Library/Logs) MB"
echo "QuickLook cache size: $(calculate_cache_size ~/Library/Caches/com.apple.QuickLook.thumbnailcache) MB"
echo ""
echo "=== Browser Cache Analysis ==="
if [[ -d ~/Library/Caches/com.apple.Safari ]]; then
echo "Safari cache size: $(calculate_cache_size ~/Library/Caches/com.apple.Safari) MB"
fi
if [[ -d ~/Library/Application\ Support/Google/Chrome ]]; then
echo "Chrome cache size: $(calculate_cache_size ~/Library/Application\ Support/Google/Chrome) MB"
fi
if [[ -d ~/Library/Application\ Support/Firefox ]]; then
echo "Firefox cache size: $(calculate_cache_size ~/Library/Application\ Support/Firefox) MB"
fi
if [[ -d ~/Library/Application\ Support/com.operasoftware.Opera ]]; then
echo "Opera cache size: $(calculate_cache_size ~/Library/Application\ Support/com.operasoftware.Opera) MB"
fi
echo ""
echo "=== Application Cache Analysis ==="
local total_app_cache=0
for container in ~/Library/Containers/*; do
if [[ -d "$container/Data/Library/Caches" ]]; then
local size=$(calculate_cache_size "$container/Data/Library/Caches")
if [[ $size -gt 10 ]]; then # Only report if > 10MB
echo "$(basename "$container"): ${size} MB"
total_app_cache=$((total_app_cache + size))
fi
fi
done
echo "Total application cache: ${total_app_cache} MB"
echo ""
echo "=== Disk Usage Summary ==="
echo "Available disk space: $(df -h / | awk 'NR==2{print $4}')"
echo "Total cache estimate: $(($(calculate_cache_size ~/Library/Caches) + total_app_cache)) MB"
} > "$report_file"
echo "📊 Report saved to: $report_file"
log_action "Cache report generated: $report_file"
}
# Selective cache clearing based on policy
clear_cache_selective() {
echo "🧹 Starting selective cache clearing based on enterprise policy..."
log_action "Starting selective cache clearing"
local total_cleared=0
# System cache clearing
if [[ "$ENABLE_SYSTEM_CACHE_CLEAR" == "true" ]]; then
echo "Clearing system cache..."
local before_size=$(calculate_cache_size /Library/Caches)
# Clear only old cache files
find /Library/Caches -type f -mtime +$CACHE_AGE_DAYS -delete 2>/dev/null
sudo find /var/log -name "*.log" -type f -mtime +$CACHE_AGE_DAYS -size +100M -delete 2>/dev/null
local after_size=$(calculate_cache_size /Library/Caches)
local cleared=$((before_size - after_size))
total_cleared=$((total_cleared + cleared))
log_action "System cache cleared: ${cleared} MB"
fi
# User cache clearing
echo "Clearing user cache..."
local before_size=$(calculate_cache_size ~/Library/Caches)
# Clear old cache files only
find ~/Library/Caches -type f -mtime +$CACHE_AGE_DAYS -delete 2>/dev/null
find ~/Library/Logs -type f -mtime +$CACHE_AGE_DAYS -delete 2>/dev/null
local after_size=$(calculate_cache_size ~/Library/Caches)
local cleared=$((before_size - after_size))
total_cleared=$((total_cleared + cleared))
log_action "User cache cleared: ${cleared} MB"
# Browser cache clearing
if [[ "$ENABLE_BROWSER_CACHE_CLEAR" == "true" ]]; then
echo "Clearing browser caches..."
clear_browser_caches
log_action "Browser caches cleared"
fi
# Application cache clearing
if [[ "$ENABLE_APP_CACHE_CLEAR" == "true" ]]; then
echo "Clearing application caches..."
clear_application_caches
log_action "Application caches cleared"
fi
# Download history clearing
if [[ "$ENABLE_DOWNLOAD_HISTORY_CLEAR" == "true" ]]; then
echo "Clearing download history..."
sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* \
'DELETE FROM LSQuarantineEvent WHERE LSQuarantineTimeStamp < datetime("now", "-30 days")' 2>/dev/null
log_action "Download history cleared"
fi
# Terminal history clearing
if [[ "$ENABLE_TERMINAL_HISTORY_CLEAR" == "true" ]]; then
echo "Clearing terminal history..."
rm -rf ~/.bash_sessions/* 2>/dev/null
rm -rf ~/.zsh_sessions/* 2>/dev/null
log_action "Terminal history cleared"
fi
echo "✅ Cache clearing completed. Total cleared: ${total_cleared} MB"
log_action "Cache clearing completed: ${total_cleared} MB cleared"
}
# Clear browser caches function
clear_browser_caches() {
# Safari
if [[ -d ~/Library/Caches/com.apple.Safari ]]; then
rm -rf ~/Library/Caches/com.apple.Safari/* 2>/dev/null
fi
# Chrome
if [[ -d ~/Library/Application\ Support/Google/Chrome ]]; then
find ~/Library/Application\ Support/Google/Chrome -name "Cache" -type d -exec rm -rf {}/* \; 2>/dev/null
find ~/Library/Application\ Support/Google/Chrome -name "GPUCache" -type d -exec rm -rf {}/* \; 2>/dev/null
fi
# Firefox
for profile in ~/Library/Application\ Support/Firefox/Profiles/*; do
if [[ -d "$profile/cache2" ]]; then
rm -rf "$profile/cache2"/* 2>/dev/null
fi
done
# Opera
if [[ -d ~/Library/Application\ Support/com.operasoftware.Opera ]]; then
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/Cache/* 2>/dev/null
fi
}
# Clear application caches function
clear_application_caches() {
for container in ~/Library/Containers/*; do
if [[ -d "$container/Data/Library/Caches" ]]; then
# Only clear if cache size is above threshold
local cache_size=$(calculate_cache_size "$container/Data/Library/Caches")
if [[ $cache_size -gt $CACHE_SIZE_THRESHOLD_MB ]]; then
rm -rf "$container/Data/Library/Caches"/* 2>/dev/null
log_action "Cleared cache for $(basename "$container"): ${cache_size} MB"
fi
fi
done
}
# Emergency cache clearing
emergency_cache_clear() {
echo "🚨 Emergency cache clearing - freeing maximum space..."
log_action "Emergency cache clearing initiated"
# Clear all user caches aggressively
rm -rf ~/Library/Caches/* 2>/dev/null
rm -rf ~/Library/Logs/* 2>/dev/null
# Clear all browser data
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Cache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/GPUCache/* 2>/dev/null
rm -rf ~/Library/Caches/com.apple.Safari/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Firefox/Profiles/*/cache2/* 2>/dev/null
# Clear all application caches
for container in ~/Library/Containers/*; do
rm -rf "$container/Data/Library/Caches"/* 2>/dev/null
done
# Clear system caches (with sudo)
sudo rm -rf /Library/Caches/* 2>/dev/null
sudo rm -rf /tmp/* 2>/dev/null
# Clear font caches
sudo atsutil databases -remove 2>/dev/null
echo "✅ Emergency cache clearing completed"
log_action "Emergency cache clearing completed"
}
# Schedule automatic cache clearing
schedule_cache_clearing() {
local schedule_type="$1"
echo "📅 Setting up automatic cache clearing schedule..."
local plist_file="$HOME/Library/LaunchAgents/com.macfleet.cache-cleaner.plist"
case "$schedule_type" in
"daily")
local interval=86400 # 24 hours
;;
"weekly")
local interval=604800 # 7 days
;;
"monthly")
local interval=2592000 # 30 days
;;
*)
echo "❌ Invalid schedule type. Use: daily, weekly, monthly"
return 1
;;
esac
cat > "$plist_file" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.macfleet.cache-cleaner</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>$(realpath "$0")</string>
<string>clear</string>
</array>
<key>StartInterval</key>
<integer>$interval</integer>
<key>RunAtLoad</key>
<false/>
</dict>
</plist>
EOF
launchctl load "$plist_file" 2>/dev/null
echo "✅ Automatic cache clearing scheduled ($schedule_type)"
log_action "Cache clearing scheduled: $schedule_type"
}
# Main execution function
main() {
local action="${1:-help}"
local target="${2:-}"
log_action "=== MacFleet Cache Management Started ==="
setup_directories
case "$action" in
"analyze"|"report")
generate_cache_report
;;
"clear")
clear_cache_selective
;;
"emergency")
emergency_cache_clear
;;
"schedule")
if [[ -n "$target" ]]; then
schedule_cache_clearing "$target"
else
echo "❌ Please specify schedule type"
echo "Usage: $0 schedule [daily|weekly|monthly]"
fi
;;
"system")
echo "🧹 Clearing system cache only..."
sudo rm -rf /Library/Caches/* 2>/dev/null
sudo find /var/log -name "*.log" -type f -size +100M -delete 2>/dev/null
;;
"user")
echo "🗂️ Clearing user cache only..."
rm -rf ~/Library/Caches/* 2>/dev/null
rm -rf ~/Library/Logs/* 2>/dev/null
;;
"browser")
echo "🌐 Clearing browser cache only..."
clear_browser_caches
;;
"apps")
echo "📱 Clearing application cache only..."
clear_application_caches
;;
"help"|*)
echo "MacFleet Cache Management Tool"
echo "Usage: $0 [action] [options]"
echo ""
echo "Actions:"
echo " analyze - Generate cache analysis report"
echo " clear - Clear cache based on enterprise policy"
echo " emergency - Emergency cache clearing (maximum space)"
echo " schedule [type] - Schedule automatic cache clearing"
echo " system - Clear system cache only"
echo " user - Clear user cache only"
echo " browser - Clear browser cache only"
echo " apps - Clear application cache only"
echo " help - Show this help message"
echo ""
echo "Schedule Types:"
echo " daily - Clear cache daily"
echo " weekly - Clear cache weekly"
echo " monthly - Clear cache monthly"
;;
esac
log_action "=== MacFleet Cache Management Completed ==="
}
# Execute main function
main "$@"
Cache Management Best Practices
Safe Cache Clearing Guidelines
Cache Type | Safety Level | Recommendation |
---|---|---|
System Cache | High Risk | Clear selectively, avoid critical system files |
User Cache | Medium Risk | Safe to clear, may reset preferences |
Browser Cache | Low Risk | Safe to clear, will re-download web content |
Application Cache | Medium Risk | Check app-specific requirements |
Download History | Low Risk | Consider privacy implications |
Performance Impact Assessment
# Measure cache clearing impact
echo "=== Before Cache Clearing ==="
echo "Available space: $(df -h / | awk 'NR==2{print $4}')"
echo "Cache size: $(du -sh ~/Library/Caches | awk '{print $1}')"
# Perform cache clearing
# ... cache clearing commands ...
echo "=== After Cache Clearing ==="
echo "Available space: $(df -h / | awk 'NR==2{print $4}')"
echo "Space recovered: [calculated difference]"
Security Considerations
- Data Loss Prevention - Always backup important data before clearing caches
- Application Impact - Some applications may need to rebuild caches after clearing
- Performance Impact - Initial performance may be slower until caches rebuild
- Privacy Implications - Clearing browser cache removes saved passwords and settings
- System Stability - Avoid clearing critical system caches without proper testing
Troubleshooting
Cache Clearing Failures
# Check for locked files
lsof | grep "Library/Caches"
# Force quit applications using cache
sudo pkill -f "application_name"
# Check permissions
ls -la ~/Library/Caches/
Disk Space Not Freed
# Force filesystem update
sync
# Check for hidden files
ls -la ~/Library/Caches/
# Verify actual deletion
du -sh ~/Library/Caches/
Important Notes
- Backup Important Data before running cache clearing scripts
- Close Applications before clearing their specific caches
- Test Scripts on individual devices before fleet deployment
- Monitor Performance after cache clearing for any issues
- Schedule Regular Cleaning to maintain optimal performance
- Document Policies for compliance and auditing purposes