Remove log files using cron job

Use wildcard. And just put it in your crontab use the crontab -e option to edit your crontab jobs.
See example:

* * * * *  find  /path/to/*.log -mtime +7 -exec rm -f {} \; 

Just to increment the answer check this nice article on how to work with your crontab ! in Linux .


You edit your personal crontab by running crontab -e. This gets saved to /var/spool/cron/<username>. The file will be the owners username, so root would be /var/spool/cron/root. Everything in the file is run as the owner of the file.

The syntax for crontab is as follows:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed

When you are editing your own personal crontab, via crontab -e, you leave out the user-name field, because the user is inferred by the filename (see first paragraph).

That being said, your entry should look like this:

0 5 * * *  find  /path/to/*.log -mtime +7 -delete

This will run every day, at 5:00 AM, system time. I don't think you need it to run any more frequently than daily, given the fact that you are removing files that are 7 days old.

Please don't use over use the -exec option, when the -delete option does exactly what you want to do. The exec forks a shell for every file, and is excessively wasteful on system resources.

When you are done, you can use crontab -l to list your personal crontab.

ps. The default editor on most Linux systems is vi, if you do not know vi, use something simple like nano by setting your environ variable export EDITOR=nano


find /path/to/dir-containing-files -name '*.log' -mtime +7 -exec rm -f {} \;

To create a cron job, put a file containing the following in the /etc/cron.daily dir:

#!/bin/sh
find /path/to/dir-containing-files -name '*.log' -mtime +7 -exec rm -f {} \;