Bash – Delete Sub-Directories with YYYYMMDD in Name Older Than N Days

bashdirectoryfindrmtimestamps

I have a directory where daily subdirectories are created, literally named according to $date. How can I delete folders and their contents that are older than 7 days according to the YYYYMMDD in the file name and not the metadata date? Say I have (skipped some for brevity):

20170817
20170823
20170828
20170901

I would end up with the following folders (which those should keep):

20170828
20170901

I created a variable that holds the date 7 days ago:
dt_prev=$(date -d "`date`-7days" +%Y%m%d)

My thought was to ls -l a list of these folder names and compare row by row, but this involves cleaning that list, etc., and I figure there has to be an easier way.

Best Answer

I think the solution would be a simpler version of what glenn jackman posted, e.g.

seven_days=$(date -d "7 days ago" +%Y%m%d)
for f in [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]; do
   [ -d "$f" ] || continue
   (( $f < $seven_days )) && echo rm -r "$f"
done

Remove the echo if the results look correct.

The -d test ensures that we only inspect (remove) directories.