Comparing dates to see if one is older than 3 months or e.g. 12 days is tricky because you'll have to compare the year, month, etc. seperately. The "date" program can also add or substract months, days, years from a date. This can be used to compare dates.
Here a bash function you can use to compare dates (in 20041219 format) in an easy, readable way:
Code:
is_older()
{
DATE=$(date -d "$1" +%Y-%m-%d)
TODAY=$(date -d "$(date +%Y-%m-%d) $2 $3 $4 $5" +%s)
COMPARE=$(date -d "$DATE" +%s)
test $(($TODAY - $COMPARE)) -le 0 && return 1 || return 0
}
You can call this function for example like this:
Code:
is_older 20041011 -3 months
is_older 20041011 -12 days
The exit code of the "is_older" function will be 0 if 20041011 is more than 3 months in the past, or more than 12 days in the past for the second example.
You can use this like this:
Code:
if is_older 20041011 -3 months ; then
echo "Older than 3 months ago."
else
echo "Younger than 3 months ago."
fi
# OR:
if is_older 20050113 -3 days ; then
echo "Older than 3 days ago."
else
echo "Younger than 3 days ago."
fi
To check your files (assuming the filenames are fixed in length, at least up to and including the date), you can use this:
Code:
#!/bin/bash
is_older()
{
DATE=$(date -d "$1" +%Y-%m-%d)
TODAY=$(date -d "$(date +%Y-%m-%d) $2 $3 $4 $5" +%s)
COMPARE=$(date -d "$DATE" +%s)
test $(($TODAY - $COMPARE)) -le 0 && return 1 || return 0
}
for FILENAME in ATK_*.dat ; do
FILEDATE=$(echo $FILENAME | cut -c 13-20)
if is_older $FILEDATE -3 months ; then
echo "$FILENAME is older than 3 months."
else
echo "$FILENAME is younger than 3 months."
fi
done
It gave me this output (on some testing files):
Code:
heiko@hko:~/dummy$ date
Fri Jan 14 14:20:32 CET 2005
heiko@hko:~/dummy$ ./filedatum.sh
ATK_7B1_WIP_20040920160700.9.xml.dat is older than 3 months.
ATK_7B1_WIP_20041010160700.9.xml.dat is older than 3 months.
ATK_7B1_WIP_20041013160700.9.xml.dat is older than 3 months.
ATK_7B1_WIP_20041014160700.7.xml.dat is younger than 3 months.
ATK_7B1_WIP_20041116160700.8.xml.dat is younger than 3 months.