I'm having a bit of trouble, I'm trying to do a script that will create a list of files and dirs older than 7 days and delete the ones that are not in the list tokeep.list. My first problem is that if I put a dir on the nodelete list, but this dir have old files inside, the files didn't get deleted, so far the only solution that I was able to do it, is to run one command for directories and other to files, it's pretty ugly, I'm no developer.

source config.cfg
exec &> >(tee $LogFile)

echo "Starting Housekeep files at $host $timestamp"

echo "Creating list of directories to delete"

cd $dir

find $dir/* -maxdepth 1 -type d -mtime +$days > /users/nordic/todelete

if [ $? -eq 0 ]; then
    echo OK
    echo FAIL

echo "deleting  directories to listed on todelete file"

dels=`cat  /users/nordic/todelete`
readarray -t keeps <  /users/nordic/tokeep

for keep in "${keeps[@]}"; do
    dels=`echo "$dels" | grep -v "$keep"`

echo "$dels" > /users/nordic/todelete

readarray -t dels < /users/nordic/todelete; for del in "${dels[@]}"; do rm -rv "$del"; done

if [ $result -eq 0 ]; then
    echo SUCCESS |tee /users/nordic/res
    echo FAILED |tee /users/nordic/res

find $dir/* -maxdepth 1 -type f -mtime +$days -print -delete

#SUBJECT="Automated Housekeep $host $resu"
#TO="[email protected]"

#mailx -s "$SUBJECT" -r "info<[email protected]>" $TO < $MESSAGE

I have a config.cfg file with the variables, what I'm trying to do is create a list of files and names of dirs to keep, and delete the rest. any suggestion is welcome.

2 Answers 2

cd "$dir" && \
find . -type d ! -name . -mtime +"$days" \
  ! -exec sh -c 'printf %s\\n "${1/./$PWD}" | grep -qFf /users/nordic/tokeep' {} {} \; \
  -print0 -prune -o -type f -mtime +"$days" -delete |\
xargs -r0 rm -r


  • Upon a successful cd into the dir. whose name is stored in $dir we
  • Launch a find command which juggles amongst the following:
    • For a directory:
      • It's not the current directory and it's older than $days then send it's name to the xargs on the other side of the pipe, provided it is not found in the tokeep file. Also do not enter into this directory since it's been marked for clearance.
    • OTW, for a file delete them if they are older than $days.
  • The xargs will be passed the old dirs that will be deleted.

I suggest creating a list of files to delete, not to keep.

And start remove dir/or files down up tree files, I'll explain better:

remove in this order:


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .