tctuvan

New Member
Deleting old files in Linux is often necessary. Often logs need to be periodically removed for example. Accomplishing this through bash scripts is a nuisance. Luckily there is the Find utility, it allows a few very interesting arguments, one of them is executing a command when a file is found. This argument can be used to call rm, thus, enabling you to remove what you find. Another argument Find allows can specify a time in which should be searched. This way you can delete files older than 10 days, or older than 30 minutes. A combination of these arguments can be used to do what we want.

First off, we need to find files older than, for example, 10 days.
find /var/log -mtime +10
You can also find files older than, say, 30 minutes:
find /tmp -mmin +30
Another argument Find accepts is executing commands when it finds something. You can remove files older than x days like this:
find /path/* -mtime +5 -exec rm {} \;

The " {} " represents the file found by Find, so you can feed it to rm. The " \; " ends the command that needs to be executed, which you need to unless you want errors like:
find: missing argument to `-exec`
Like i said, {} represents the file. You can do anything with a syntax like this. You can also move files around with Find:
find ~/projects/* -mtime +14 -exec mv {} ~/old_projects/ \;

Which effectively moves the files in ~/projects to ~/old_projects when their older than 14 days.
 

Các chủ đề có liên quan khác

Top