Deleting files automatically using bash

bashlinuxshell

I have a directory /backup that contains other directories with daily backups in them. Those directories are sorted by name and date (BACKUP_date). The few lines of bash script which i had been using before worked until the beginning of a new month and stopped due to some unforeseen situations. this was what i used previously

#!/bin/bash

ndate=$(date "+%Y%m%d")
ndays=8
ddate=$((ndate-ndays))

cd /backup || exit
rm -rf BACKUP_$ddate

How can i modify this to be much more intelligent.

Best Answer

If you echo the values, it is obvious what goes wrong:

a=$(date "+%Y%m%d")
echo $a
20210906
b=$(($a-8))
echo $b
20210898

There is no 98th day in August.

So, a beter way would be to let date do the calculation:

b=$(date "+%Y%m%d" --date='8 days ago')
echo $b
20210829
Related Question