Issue
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.
Solution
You can use the date
command to find the date 90 days earlier to the current one. The following script should give you a list of directories that need to be deleted:
del=$(date --date="90 days ago" +%Y%m%d)
for i in `find . -type d -name "2*"`; do
(($del > $(basename $i))) && echo "delete $i" || echo "dont delete $i"
done
To perform the actual deletion of directories, you can replace the third line with the following:
(($del > $(basename $i))) && rm -rf $i
For example, if your current directory contains the following folders:
$ ls -1F
20120102/
20130104/
20130302/
20130402/
20130502/
20130602/
20130702/
Executing the above script would tell:
$ bash cleanup
delete ./20130302
delete ./20130104
delete ./20120102
delete ./20130402
dont delete ./20130702
dont delete ./20130502
dont delete ./20130602
Answered By - devnull Answer Checked By - Katrina (WPSolving Volunteer)