BASH
Clean Up Old Build Artifacts and Cache Files
Automate cleanup of old build artifacts, temporary files, or cache directories in web projects to free up disk space and maintain tidiness.
#!/bin/bash
# Configuration
CLEANUP_ROOT="/var/www/mywebapp" # Root directory to start cleanup
DAYS_OLD="+7" # Files/directories older than 7 days will be deleted
EXCLUDE_DIRS=("node_modules" ".git" "vendor") # Directories to exclude from deletion
echo "Starting cleanup in ${CLEANUP_ROOT} for files older than ${DAYS_OLD} days..."
# Build the find command with exclusions
FIND_CMD="find ${CLEANUP_ROOT} -type f -mtime ${DAYS_OLD}"
for dir in "${EXCLUDE_DIRS[@]}"; do
FIND_CMD+=" -not -path '*/${dir}/*'"
done
# Find and delete old files
# IMPORTANT: Use -print0 and xargs -0 for filenames with spaces/special characters
# Use `echo` before `rm` for a dry run
eval "${FIND_CMD} -print0 | xargs -0 rm -v"
# To just list files without deleting:
# eval "${FIND_CMD} -print0 | xargs -0 -I {} echo {}"
echo "Cleanup complete!"
How it works: This script helps clean up old files in a specified directory, useful for removing outdated build artifacts, cache files, or logs from web projects. It uses `find` to locate files older than a configured number of days, while also allowing specific directories (like `node_modules` or `vendor`) to be excluded from the cleanup process. The script performs the deletion using `xargs rm -v` after finding the files.