LINUX: Removing Files Older Than x Days

It can often be use­ful to remove files that are unnec­es­sary, such as log files, back­up files, etc, when it is not already done auto­mat­i­cal­ly. For­tu­nate­ly there is a very sim­ple com­mand to do just that.

Using the find com­mand, it is pos­si­ble to find the files in the fold­er you want to clean out and remove them. The fol­low­ing com­mand scans the fold­er /home/myuser/myfolder/ for files old­er than 30 days and then exe­cutes rm, to remove those files.

find /home/myuser/myfolder/* -mtime +30 -exec rm {} \;

If you want to be cau­tions, you can use the fol­low­ing com­mands to test it out:

To see what find pulls up, you can run this.

find /home/myuser/myfolder/* -mtime +30

If you want to make cer­tain the exec com­mand is given the right para­me­ters, you can run it through ls.

find /home/myuser/myfolder/* -mtime +30 -exec ls -l {} \;

Leave a Reply

Your email address will not be published. Required fields are marked *