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.

Examples

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
➜  find . -type d -mtime +5 -exec ls -ld {} \;

#delete
➜  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.

Examples

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

➜  vim scheduledCleanFiles.sh
#!/bin/bash
find /var/log/ -type f -mtime +5 -exec rm -rf {} \;
find /var/log/ -type d -mtime +5 -exec rm -rf {} \;

➜  chmod +x scheduledCleanFiles.sh

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

➜  vim /etc/crontab

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

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.