delete folder in linux

How to Delete Folders Older than 7 Days in Ubuntu

System administrators often need to delete files & folders older than X days on their system. In this article, we will learn how to delete folders older than 7 days in Ubuntu. You can use these steps to delete files & folders older than any number of days as per your requirement. You can also use these steps on almost any Linux distribution.


How to Delete Folders Older than 7 Days in Ubuntu

Here are the steps to delete folders older than 7 days in Ubuntu. You can easily do this using find command. Here is the command to delete files & folders in /data/ folder, that are older than 7 days.

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

The first argument is the path to folder whose content you want to delete. It can be relative or absolute path, and can contain wildcard characters like *. Next option is -mtime that stands for last modified time. If we enter +7 after -mtime, find command will look for all files older than 7 days.

The third argument -exec is used to execute any specific Linux command, on the files that have been found as a result of find command. We mention rm {} to delete all files older than 7 days, in /data/ folder.

If you want to delete only folders, add type -d option to find folders, and use rmdir command.

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

If you want to delete both files & folders, use rm -r command.

$ find /data/*/* -mtime +7 -type d -exec rm -r {} \;

If you want to create cronjob just open crontab with the following command.

$ crontab -e

Add the following line to run the above find command every day at 10.A.M.

0 10 * * * find /data/*/* -mtime +7 -type d -exec rm -r {} \; >/dev/null 2>&1

Save and close the file. You can easily generate cronjob commands using an online crontab generator.

In this article, we have learnt how to find & delete files & folders older than 7 days in Linux.

Also read:

NGINX Prevent Host Header Attack
How to Enable IP Forwarding in Linux
How to Delete Commits in Git
How to Set User Agent in cURL
How to Unzip File in Linux

Leave a Reply

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