Delete the files older than 3 weeks in a particular directory.

Hi, Friends,
I am writing a script to delete all the files which are there for more than 3 weeks.

I have tried this :
find /home/appl/backup -type f -mtime +21 -exec rm -f {} \;

But i am not sure if it deletes only the files in specified directory or all the directorinies in the provieded to it.

I tried subtracting the present week and week in which files were last modified.And thus delete all of the remaining.When i do ls -lt to get modification date, i cudnot get the week number from the old files' modification date.

Please suggest a way out ASAP.And any help in this regard will be appreciated in advance...

Try testing your code. Setup some test directories and files. you can use the touch command to create files and change the date on the file. Create some files and directories that would fall within your delete window and some that don't. you can even create a script to generate these test files to make it easily repeatable.

mkdir tst
ls -lrt
drwxr-xr-x 2 user usrgrp 4096 Nov 14 18:02 tst
touch -t 200910121314 tst
ls -lrt
drwxr-xr-x 2 user usrgrp 4096 Oct 12 13:14 tst
touch -t 200910121314 tfile.tst
ls -lrt

drwxr-xr-x 2 user usrgrp 4096 Oct 12 13:14 tst
-rw-r--r-- 1 user usrgrp    0 Oct 12 13:14 tfile.tst

Whenever I am writing a script that removes files, I always have the script list the files the script has targeted for removal and verify those are the files I expect before I implement the rm command.

Good luck.

You will almost certainly want to look at the prune option for find as well

  1. You can first execute the find command without -exec part, to view the list as,
find /home/appl/backup -type f -mtime +21
  1. If you are want to double ensure you are removing only the intended file then use -ok instead of -exec which will ask confirmation from you before doing the specified operation on each file.
 find /home/appl/backup -type f -mtime +21 -ok rm -f {} \;