Warning: count(): Parameter must be an array or an object that implements Countable in /home/mikestec/public_html/ubuntu-antenna/wp-content/plugins/wordpress-ping-optimizer/cbnet-ping-optimizer.php on line 533

Delete Files So Many Days Old in Ubuntu

Delete files so many days old in Ubuntu

Delete files so many days old in Ubuntu

Recently on one of my Ubuntu servers, I needed to delete files that were older than a week. Here is how I did it:

By using Ubuntu’s find command with a few options, will take care of what I need to do. Here is the command that I used:

find /path_to_files/* -type f -mtime +7 -exec rm -rf {} \;

OK, let me explain the syntax of the find command above:

The first part is the path that you want find to search. Wildcards are permitted, as shown in the command above.

The option -type f tells the find command to search for just files (more on this later).

The option -mtime +7 is what sets the number of days old the file needs to be. In this case, we are looking for all files older than 7 days old.

The option -exec  lets me pass a command on to a new process that satisfies the find command. In this case, we want to rm -rf which recursively deletes what we want from whatever folder in the specified file path, and forces the operation.

Its very important to make sure that there are spaces between rm -rf, {}, and \;  if you get an error, this is the first place to look.

Like I mentioned earlier, the -type f option just deletes files. In my situation I still had a bunch of empty directories that weren’t deleted. The solution to this is, after you have executed the above command and deleted the files, change the option to a -type d and re-run the command. This will delete the directories.

Then just place the find command into cron and set it to regularly run as you like.

This article was originally posted on www.mikestechblog.com Any reproduction on any other site is prohibited and a violation of copyright laws.