Easily Automatically Delete Linux Log Files Older Than 30 Days Using a Bash Script

Bash Script to Remove Linux Older Than 30 Days Automatically

Log files are necessary for monitoring system activity and resolving problems. But they can build up and take up a lot of disk space over time. You can keep your system clean by automatically deleting these outdated files with a straightforward Bash script.

Prerequisites:

Before you start, make sure you have:

  • A Linux system or server.
  • Basic knowledge of using the terminal.
  • Access to the directory where log files are stored.
  • Permission to delete files in that directory.

Why Clean Up Log Older Files:

Old log files can:

  • Take up unnecessary disk space.
  • Make directories cluttered.
  • Slow down backups or maintenance tasks.

Cleaning them regularly keeps your system organized and efficient.

ALSO READ:

Click here to go to the GitHub repos link

Create the Bash Script

#!/bin/bash

# Directory where log Older files are stored
LOG_DIR="/path/to/logs"

# Delete log Older files older than 30 days
find "$LOG_DIR" -type f -name "*.log" -mtime +30 -exec rm -f {} \;

echo "Deleted log Older files older than 30 days from $LOG_DIR"

Make the Script Executable & Execute your script

chmod +x 30_days_lod_logs_delete_script.sh
./30_days_lod_logs_delete_script.sh

Automate Cleanup Using Cron:

To ensure your logs are cleaned regularly, schedule the script with a cron job:

    crontab -e
    

    Add the following line to run the script daily at midnight:

    0 0 * * * /path/to/30_days_lod_logs_delete_script.sh >/path/status.log
    

    This ensures your logs are managed automatically without any manual effort.

    Best Practices

    • Backup important logs: Save any critical logs before deleting.
    • Test first: Run the script manually once to check it works correctly.
    • Set your own time: Change +30 the command if you want to keep logs for more or fewer days.

    Thank you.

    Leave a Comment

    Index