Clean Linux Log Directory Script


The more you use your Linux based system, the more files will be created. One thing that I noticed with mine is that the log directory would continue to grow. When I used Webmin, it had the ability to clean up certain directories, like the /var/log directory, built into it. They just had to be turned on.

Now depending on the program that is creating a log, those log files will stay in there for a log time and be very significant in size. I wasn't aware of this, but Apache was one of the main programs that was creating log files. These files would be come rather large on my development and test environments because of the work that I was doing.


The solution was to create a script that would clean up the log directory and do this on a predefined schedule. For me, I set this job to run monthly and keep at least the last 14 days worth of logs.

Word of Caution

If you are going to use this script, I would advise not setting the DELAY variable to 0. The reason being is that the script will delete the log files that are currently being used by the application. As a result, those files may be locked by the application. Also, delete the files, may cause the application to crash.

The Script



if [ "$(id -u)" == "0" ]; then
    cd /var/log 

    # display the disk usage before cleanup
    # /bin/df -h .
    /usr/bin/du -sh /var/log

    # list all the files before removing
    /usr/bin/find /var/log/* -type f -mtime +${DELAY} -exec ls -la {} \;

    # remove the files
    /usr/bin/find /var/log/* -type f -mtime +${DELAY} -exec rm {} \;

    # list files in backup directory
    /usr/bin/find /var/backups/* -type f -mtime +${DELAY} -exec ls -la {} \;

    # remove files
    /usr/bin/find /var/backups/* -type f -mtime +${DELAY} -exec rm {} \;

    # display the disk usage after cleanup
    # /bin/df -h .
    /usr/bin/du -sh /var/log
    echo "ERROR: Must be root to run script."
Updated: 2023-06-03 | Posted: 2016-05-29
Author: Kenny Robinson, @almostengr