using shell script: file name date string compare with current date

Viewed 46

Hi Unix and Shell script experts, I want a script. Every friday (20220909 for example) I am getting three file

20220909_abc.txt
20220910_abc.txt
20220911_abc.txt

with shell script I need to check this three files, get the YYYYMMDD part, and need to cross check with latest dates (today /tomorrow/next day), if they match continue else fail

20220910_abc.txt--->20220910-->next day..i.e 20220910 (which current date+1)

20220911_abc.txt--->20220911-->next day..i.e 20220911 (which current date+2)

If we got any file out of range (like older than 20220909 or greater than 20220911), need to fail. Appreciate you provide some insight on this.

1 Answers

Didn't really spend much time but assuming you are trying to compare the dates with filenames like 20220910_abc.txt

you can use the following snippet

# get the latest date
latest_date=$(date +%Y%m%d)
echo "latest date is $latest_date"

# get the next day date
tomorrow=$(date -v+1d +%Y%m%d)
echo "tomorrow day is $tomorrow"

# get the next day date
day_after_tomorrow=$(date -v+2d +%Y%m%d)
echo "day after tomorrow day is $day_after_tomorrow"

# get the file name
file_name="20220913_abc.txt"
echo "file name is $file_name"

# get the file date
file_date=$(echo $file_name | cut -d'_' -f1)
echo "file date is $file_date"

# check if the file date is equal to latest date
if [ $file_date -eq $latest_date ]
then
    echo "file date is equal to latest date"
else
    echo "file date is not equal to latest date"
fi

# check if the file date is equal to tomorrow date
if [ $file_date -eq $tomorrow ]
then
    echo "file date is equal to tomorrow date"
else
    echo "file date is not equal to tomorrow date"
fi

# check if the file date is equal to day after tomorrow date
if [ $file_date -eq $day_after_tomorrow ]
then
    echo "file date is equal to day after tomorrow date"
else
    echo "file date is not equal to day after tomorrow date"
fi

Running

╰─ bash test.sh
latest date is 20220911
tomorrow day is 20220912
day after tomorrow day is 20220913
file name is 20220913_abc.txt
file date is 20220913
file date is not equal to latest date
file date is not equal to tomorrow date
file date is equal to day after tomorrow date
Related