BASH
Automatically Clean Up Old Log and Temp Files
Learn to create a Bash script that automatically identifies and deletes old log files or temporary files from a specified directory, preventing disk space issues.
#!/bin/bash
# Configuration
CLEANUP_DIR="/var/log/my-web-app" # Directory to clean
RETENTION_DAYS=30 # Files older than this many days will be deleted
EXCLUDE_PATTERN="important.log" # Files matching this pattern will be skipped (e.g., "*.gz" for compressed logs)
# --- Functions ---
log_message() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}
# --- Main Script ---
log_message "Starting cleanup in directory: $CLEANUP_DIR"
if [ ! -d "$CLEANUP_DIR" ]; then
log_message "ERROR: Directory $CLEANUP_DIR does not exist."
exit 1
fi
log_message "Searching for files older than $RETENTION_DAYS days (excluding '$EXCLUDE_PATTERN')..."
# Find and delete files
find "$CLEANUP_DIR" -maxdepth 1 -type f \
-name "*" ! -name "$EXCLUDE_PATTERN" \
-mtime +"$RETENTION_DAYS" \
-print -exec rm -f {} \; \
| while read -r file; do
log_message "Deleted: $file"
done
if [ $? -ne 0 ]; then
log_message "WARNING: Some errors might have occurred during file deletion."
else
log_message "Cleanup completed."
fi
log_message "Finished cleanup in directory: $CLEANUP_DIR"
How it works: This script helps manage disk space by automatically deleting files older than a specified number of days in a target directory. It uses the `find` command to locate files, excludes certain patterns (like active or important logs), and then removes them. This is ideal for managing server logs or temporary build artifacts.