For example, let’s say you currently do non-incremental backups of your data on a daily business. If you don’t keep an eye on it, pretty soon your backup folder will run out of space and your system would come crashing down – so maybe it isn’t such a bad idea to run a cron in the background that deletes unnecessary files that are older than a specified number of days.
So how do we do this?
Well one solution is to make use of the powerful little find utility that comes with pretty much any variant of Linux. What this littly beauty does is offer you a whole lot of useful arguments, one of the most interesting being that of specifying a command to run on each file found!
Leveraging this functionality, we will first use the find command to locate our files older than a nuber of days and then use the rm command to delete them.
So how would the syntax for this look then?
find /path/to/files* -mtime +7 -exec rm {} \;
(Note the spaces between rm, {} and \;)
The first argument is the path to the files, it being either a path, directory or even a wildcard as indicated above. Full path is probably the safest though!
The second -mtime argument is used to specify the number of days old a file needs to be in order to qualify for the search. If you enter +7 like we have, then find will return all files older than 7 days.
Finally, the -exec attribute allows us to pass our command (like rm) to the find function and apply it against each of the located files. The {} \; at the end is simply a control sequence to terminate the command.
Nifty.
You might also enjoy:
-
To generate a back up of a crontab file is actually pretty simple, making use of the built in -l switch that comes with the command: sudo crontab -l > ~/ ...
-
The following function is useful if you wish to clear out all files and folders currently sitting in one particular directory. The function itself requires ...
-
If you work as a web developer with PHP and all of a sudden you need a script to do something specific for you on a system (say as a cron job or such), ther ...
-
If you are new to Linux then chances are high that the damn terminal and sudo command combination are not yet second nature to you, and as such you would mu ...
-
A quick way to stop or start a particular process running as a system daemon on your Ubuntu box is to make use of the start-stop-daemon command. Usag ...