How to find and delete old linux files or directories

During server operation and maintenance, we often need to clean up log files to save storage space.

So how do you find and clean up these old files or directories?

At this time we will use the linux find command and the linux rm command.


Find and Delete files older than 5 days in linux

1.find files older than 5 days

➜  find . -type f -mtime +5 -exec ls -l {} \;

2. delete files older than 5 days

➜ find . -type f -mtime +5 -exec rm -v {} \;

Find and delete directories older than 5 days in Linux

➜  find . -type d -mtime +5 -exec ls -ld {} \;

➜  find . -type d -mtime +5 -exec rm -v {} \;

How to find and delete old files or directories on a scheduled tasks?

The above method can manually clean up old files, but sometimes we prefer this operation to be done automatically, such as performing a cleanup operation at 1 AM every day.

At this time, we need to use the linux crontab command.


1. Write a shell script that can delete old files and grant executable permissions

➜  vim
find /var/log/ -type f -mtime +5 -exec rm -rf {} \;
find /var/log/ -type d -mtime +5 -exec rm -rf {} \;

➜  chmod +x

2. Configure crontab scheduled tasks to run every day at 1 AM

➜  vim /etc/crontab

0 1 * * *   ylspirit    /usr/bin/sh /home/ylspirit/

Of course, the commands to be executed can also be configured directly into the contab file.

0 1 * * *   ylspirit    find /home/ylspirit/ -type f -mtime +5 -exec rm -rf {} \;

Add a Comment

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