[HOW TO] delete files older than x days

Sometimes in Linux, you want to clear older file than x day in a directory.

In this article, I show you how to create a script and set crontab in this case.

Step 1: Script

#!/bin/bash
find /tmp/* -mtime +5 -exec rm {} \;

find: the command will search for the files/folders
/tmp/*: the direcroty to start searching
-mtime +5 files older than 5 days.
-exec: what to do with the files we found.
rm remove them
{} this represents each file we found.
\; the end of the exec.


#!/bin/bash
find /tmp/orion/* -mmin +1 -exec rm -rf {} \;

find: the command will search for the files/folders
/tmp/orion/*: the direcroty to start searching
-mmin +1 files older than 1 minute.
-exec: what to do with the files we found.
rm -rf remove them recursively, force.
{} this represents each file we found.
\; the end of the exec.


#!/bin/bash
find /tmp/orion/* -type f -mmin +1 -exec rm -rf {} \;

find: the command will search for the files/folders
/tmp/orion/*: the direcroty to start searching
-type f: don't remove directories, only files.
-mmin +1 files older than 1 minute.
-exec: what to do with the files we found.
rm -rf remove them recursively, force.
{} this represents each file we found.
\; the end of the exec.

#!/bin/bash
find /tmp/orion/* -name "*.log" -type f -mmin +1 -exec rm -rf {} \;

find: the command will search for the files/folders
/tmp/orion/*: the direcroty to start searching
-name find name
-type f: don't remove directories, only files.
-mmin +1 files older than 1 minute.
-exec: what to do with the files we found.
rm -rf remove them recursively, force.
{} this represents each file we found.
\; the end of the exec.

Step 2: Set Crontab

Firstly, we need to know the structure of Crontab as below:

*     *     *     *     *     command to be executed
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- day of week (0 - 6) (Sunday=0)
|     |     |     +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

with * tasks to run with all values ​​in that column

Ok, let it go.

You can create the crontab:


0 2 * * * /bin/find /path/to/files/ -type f -mtime +5 -exec rm {} \;

This will run rvery night at 2:00 AM.

Also:


0 2 * * * sh /path/del.sh 

Done,

Thank you. Now I'm going to sleep :)
See you soon,




Thank you for reading this article, please a comment if you are interested.
Tiến Phan - R0039
Knowledge is Endless
Sharing for Success

0 nhận xét:

Post a Comment