I'm very new in bash scripting and I'm really stuck on the find method from Ubuntu. I want to search in the folder /opt/ for all folders to see if they are older than a specific date. If they are older the files in this folder should be removed (and the folder itself too actually). If the date is still too new the files should not be touched.

What I have in code:

find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*$mystring" -exec rm -rf '{}' ';'

The variables contain these values:


If the variable $DAYS_TO_KEEP is 2, the date is 2014-11-25 and the folder name is 2014-11-20-daily_testmachine the folder and its contents should be dropped.

What am I doing wrong that find is not removing/finding these files and folders to remove? I can't seem to find the error.

Note: if I execute the command with the exact string name of the folder in it the folder will be deleted. So I have something wrong in my format or naming.

find $BACKUP_DIR -maxdepth 1 -name "2014-11-20-daily_testmachine" -exec rm -rf '{}' ';'

To make things more clear I've made a screenshot to show the setup:

  • 1
    I don't see any errors. Are you sure that folder are older than DAYS_TO_KEEP? Command with fixed name, maybe works because -mtime is missing :) – Lety Nov 25 '14 at 22:49
  • I was exactly thinking about this last evening and turned out this was a big part of the problem! And minor tweaking of the logic. Thanks Letizia! – Yenthe Nov 26 '14 at 8:51

My error was a logic error with -mtime. I thought my script was checking the names but -mtime checks for the date when the file was created. So my final code:

find $BACKUP_DIR -maxdepth 1 -mtime +"$DAYS_TO_KEEP" -exec rm -rf {} \;

I just had to do a sudo touch -d "3 days ago" /filepath/folderToRemove to make -mname find the folder and make sure the file was old enough to be removed. So this final code removes all folders that are older than my variable $DAYS_TO_KEEP

  • 1
    Try this, I think that can be useful to understand how find and file mtime date works. – Lety Nov 26 '14 at 9:23
  • Thanks for the link, this looks great to find out more about it! – Yenthe Nov 26 '14 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.