Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete directory based on date

Tags:

date

unix

I am writing zsh script in which I have to get the date of 90th previous day from current date i.e I have to subtract 90 days from current date. Then I have to check the folders which have different dates as their names. I have to compare the directory date with the subtracted date and if the result is greater than the subtracted date, I have to delete the directory.

For example:

Let us say the current_date = 20131130 (yyyymmdd)

subtracted_date=current_date - 90 days

lets say there is a folder 20130621

Now this folder name should be compare with the subtracted date. If greater than subtracted_date then i have to delete the directory.

like image 237
Jahnavi Avatar asked Aug 23 '26 04:08

Jahnavi


2 Answers

find path -type d -ctime +90 -exec rm -rf {} \;

should find all directories older than 90 days and use rm -rf on them

Be careful with that command though you will probably want to test it first with this

find path -type d -ctime +90 -exec echo {} \;

in order to keep certain folders consider -mtime instead of -ctime and touch the folder every so often

replace path above with the actual path you want to scan and delete

explanation

find is the command

path is the root directory you want to scan

-type d means look for directories only

-ctime +90 means created time older than 90 days

-exec rm -rf {} \; means remove recursively and force delete of the items which were found

-mtime is modified time

The second command will list out all folder which will be deleted so is much safer to run while you are testing

like image 78
exussum Avatar answered Aug 25 '26 18:08

exussum


List directories before delete

find . -type d -ctime +60  -ls

List files before delete

find . -type f -ctime +60  -ls

Delete directories in current directory

 find . -type d -ctime +60 -exec rm -rf {} \;

Delete files in current directory

  find . -type f -ctime +60 -exec rm -rf {} \;
like image 28
PodTech.io Avatar answered Aug 25 '26 18:08

PodTech.io



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!