1

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.

LogFile=/users/nordic/housekeep.log
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
else
    echo FAIL
fi

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"`
done

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

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

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

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

#SUBJECT="Automated Housekeep $host $resu"
#TO="nordic@blah.com"
#MESSAGE="$LogFile"

#mailx -s "$SUBJECT" -r "info<sysdm@blah.com>" $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.

0
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

Working

  • 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.
0

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:

/dir1/dir2/file2
/dir1/dir2
/dir1/file1
/dir1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.