Deleting files older than 14 days automatically

Hi

In my aix server under the location "/usr/sap/SAPXI/extract", I have a lot of log files.

I need a script which is to be added in crontab so that the files and directories older than 14 days should get deleted automatically from the location "/usr/sap/SAPXI/extract".

Please advise me. Thanks

Create script like this:

#!/bin/sh
find /usr/sap/SAPXI/extract -type f -mtime +14 -exec rm {} \;
1 Like

If you want to delete the directories as well remove

-type f

from the command. Also be aware that if the extract directory ever meets the 14 day criteria that it will be deleted as well. Maybe someone else knows how to exclude the base search directory when using the find command, as I don't. You could avoid this by touching the directory before running the find command which just updates the time stamps on that directory. Not likely to be an issue if this directory is accessed and written to often but wanted you to be aware of it.

#!/bin/ksh
touch /usr/sap/SAPXI/extract
find /usr/sap/SAPXI/extract -mtime +14 -exec rm -rf {}\;

Also be aware that

-mtime

deals with modifed time. You may have files in that directory that are being accessed but not modified so you may consider using

-atime

value to cover yourself there, that is if access times are a factor in your environment.

This is difficult to achieve. The moment you delete a file or directory, the timestamp on the directory containing that file or directory changes. Unless this is a very simple tree "rm -rf" is out of the question because it is not unusual for subdirectories to have a later modification time than the parent.
If the requirement matches it may be better to delete old files then susequently delete empty directories from the bottom of the tree up (not an easy script).