linuxshellautomation

find and delete file or folder older than x days


I want to delete file and folder older than 7 days so I tried

[17:07:14 root@client01.abc.com:~]# find /tmp/ -mindepth 1 -maxdepth 1 -ctime +7 -exec ls -l {} \;

So when I run find /tmp/ -mindepth 1 -maxdepth 1 -ctime +7 -exec ls -l {} \; it doesnt show any dir, but for find /tmp/ -mindepth 1 -maxdepth 2 -ctime +7 -exec ls -l {} \; it does show few files in subdir.

Whats is the right way to delete files/folders older than 7 days in one specific dir ?


Solution

  • You can make use of this piece of code

    find /tmp/* -mtime +7 -exec rm {} \;
    

    Explanation

    Source : http://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/

    For deleting folders, after emptying inside of them you can rmdirinstad of rm in the piece of code, also if you only want to see directories you can add

    -type d
    

    to piece of code such as below:

    find /tmp/*/* -mtime +7 -type d -exec rmdir {} \;