Deleting files automatically using bash

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

Don't treat times or Y-M-D dates as plain integers; they have gaps in the value range and ordinary integer operations don't account for them. For example, if your script runs on September 6th, it calculates "ddate" as August 98th, because 2021_09_06 - 8 = 2021_08_98.

There are three ways to make this work:

Date formats which are integers

The %s format will give you the date+time as a "Unix timestamp" in seconds since Jan 1, 1970. This is an integer and you can simply add or subtract seconds from it:

ntime=$(date +%s)
ndays=8
dtime=$(( ntime - ndays*86400 ))

Once you have the timestamp for "8 days ago", you can ask date to format it using -d @12345:

ddate=$(date -d "@$dtime" +%Y-%m-%d)

Let date do the calculation

If you want to get a date 8 days ago, you can get it directly using -d "8 days ago":

ndays=8
ddate=$(date -d "${ndays} days ago" +%Y-%m-%d)

(This can be stacked but in a slightly non-obvious way, e.g. "4 days ago 12 hours ago" instead of just "4 days 12 hours ago".)