Script to delete jobs more then 8 days

Viewed 29

I wrote a script to go into that workspace and delete jobs that are more than 8 days.

The script is mean to go in to the sub-directories (folder inside folder and inside it jobs) and delete anything more than 8 days

It delete some jobs in some directories and leave some without deleting.

Error shows: cannot delete, directory is not empty

!/bin/bash

directory="/home/jenkins/workspace/"

cd $directory && find . -mtime +8 -delete
echo $directory deleted

Your input is highly welcome Thanks

2 Answers

The logic that's correct for files isn't also correct for directories: a directory can be older than 8 days but still be undeletable (because it has files under it that were last modified less than 8 days ago).

The easy thing to do (because it takes order-of-operations questions out of play) is to split this into two separate find calls, first deleting old files, then deleting empty directories:

find "$directory" -mtime +8 -type f -delete
find "$directory" -mindepth 1 -type d -empty -delete

There are many reasons why you may end up trying to delete non empty directories

  • Maybe (main possible reason, depending on the unknown structure of what you call jobs) you have >8 days old dir containing <8 days files (the file cannot be <8 days since creating a file in the dir should change that dir mtime. But it could be a >8 days file that has been recently updated. Then dir mtime is unchanged)
  • Maybe you have a new file in a old sub sub dir of an old directory. So, can't delete the dir
  • Or permissions making impossible to empty a dir. Or special files...

But, well. You can't delete an empty dir. And from what you've shown nothing prove that there can't be new (undeleted) files in an old dir. And in that case your script will try to -delete that dir.

Related