Remove logs older than x days

Written by Robert -

Logrotate can be a handy tool, but sometimes, a simple bash script can be easier.
In my situation, samba writes log files to /var/log/samba. This only creates small files that I don't need for a long time. I'm going to create a script to remove the log files that are older than 30 days.

First I need to create a file (it only likes uppercase, lowercase, digits, underscores and dashes, so removelogs.sh would not be executed):

vim /etc/cron.daily/removelogs

Now we can create a simple script

#!/bin/bash
# Remove files older than 30 days.
find /var/log/samba/* -maxdepth 1 -mtime +30 -maxdepth 1 -exec rm {} \; > /var/log/logsdelete.log
# find: find files in location
# maxdepth: how far it should search. 1 is only top directory it's searching in. leave this out to 
# search everything below the folder.
# mtime: only display files older than +n days
# exec: execute rm on output
# >: write log file to .log


The comments in this script should make sense. You can easily change the time or location, or add more rules to different folders where you need the same thing done.

Now that the script is in place, we can save the script and make it executable.

chmod +x /etc/cron.daily/removelogs