Script That Can navigate to 3 differents directory & remove files under them

Hi

I am Trying to Write a script that can goto 4 different directorys on the server & remove the Files older then 30 days ??

/logs

logs1 logs2 logs3

Now I need to remove files under

logs1 logs2 logs3 which are older then 30 days whose name stat 'sit' , 'mig','bld' .

in addition

I have another directory which residing some where else i also need to remove file in that directory which is under root as /log4 are older then 30 days

I have this as of now ..

vi Archive_logscript

#!/bin/bash

cd /log/log1

find . -type f -name 'sit_*' -mtime +30 -print | xargs /bin/rm -rf

cd /log/log2

find . -type f -name 'mig_*' -mtime +30 -print | xargs /bin/rm -rf

cd /log/log3

find . -type f -name 'bld_*' -mtime +30 -print | xargs /bin/rm -rf

cd /oldfiles/log4

find . -type f -name 'pro_*' -mtime +30 -print | xargs /bin/rm -rf

exit

-----

do you think this works ??? any better suggestion ???

You do not need to cd into each directory in turn, you can specify the full path, this is also safer in that if the cd failed the find would have still run, e.g.:

find /logs/logs1

You can replace:

with

-exec rm {} \;

The -r would do a recursive delete which should not need to apply to a file, the -f may still be necessary depending on the permissions on the files you are deleting.

If you must cd into each directory first then do:

cd /directory && find . -type f -name...

So that if the cd fails then the find does not run.

Thanks Tony ..
I will implement and then see what happens ..

you can first find older directories than 30 days, then move them under a spesific directory you create, lets say /old_dir_tree then remove the ones you want: modifying this code:

mkdir /old_dir_tree
find . -type d -mtime +30 | grep -i 'log1 log2 log3' >> old_dir.txt
while read line;
        do
        mv $line /old_dir_tree
done<old_dir.txt

if you like you can also grep some spesific directories in all found old directories, then remove only them.

Or you can directly remove old directories with this command but i dont recommend this way:

find . -type d -mtime +30 -exec rm -r {} \;

try to modify the first code.

regards