Ubuntu – Find not removing files in folders through bash script

14.04bashfindscripts

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:

BACKUP_DIR=/opt/
TESTDIR=2014-11-25-daily_testmachine
mystring=-daily_testmachine

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:

Best Answer

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:

DAYS_TO_KEEP=2
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