Write a Bash script to find and delete log files older than 30 days.
#!/bin/bash
# Delete log files older than 30 days in /var/log/myapp
LOG_DIR="/var/log/myapp"
DAYS=30
DRY_RUN=false # Set to false to actually delete
if [ ! -d "$LOG_DIR" ]; then
echo "Directory $LOG_DIR does not exist"
exit 1
fi
if [ "$DRY_RUN" = true ]; then
echo "Dry run — files that would be deleted:"
find "$LOG_DIR" -name "*.log" -mtime +$DAYS -print
else
echo "Deleting log files older than $DAYS days..."
find "$LOG_DIR" -name "*.log" -mtime +$DAYS -delete
echo "Done. Freed up space:"
df -h "$LOG_DIR"
fi
Always implement a dry run mode. Schedule this with cron or use logrotate for production systems.