Calculate time stamp difference

Hi All,

I am new to shell scripting.I have to write a shell script for the problem statement:

"A file is updated continously. If it is not updated for a day then an error message needs to pop up."

So the script needs to read the last modified time of that file and current system time .If the difference is more than 1 day then error message needs to be displayed.

Any help is much appreciated.:slight_smile:

Thanks,
Bharath

Run below script using

<scriptname> <filename>

filename=$1
filetimestamp=`ls -lrt $filename| awk '{print $7}'`
current_date=`date +%d`
a=`expr $current_date - $filetimestamp`
if [ $a -le 1 ] ; then
echo "File was last updated on `date`"
else
echo "File was not updated from one day"
fi

Cheers
Harish

1 Like

Harish,

Thanks a lot for your quick response.

Can you please help me further in modifying code so that 24 hours difference is calculated in accurate sense.

That is calculating 24hrs diiference taking into consideration date, month and year also into consideration.:slight_smile:

Regards,
Bharath

Bharath,
Please check below code and try to run using

<scriptname> <filename>

filename=$1
filedate=`ls -lrt $filename| awk '{print $7}'`
filetimestamp=`ls -lrt $filename | awk '{print $8}' |awk -F ":" '{print $1 $2}'`
fileyear=`ls -lrt $filename | awk '{print $8}'`
filetime=`ls -lrt $filename | awk '{print $8}'`
filemonth=`ls -lrt $filename | awk '{print $6}'`
current_month=`date +%c | awk '{print $2}'`
current_year=`date +%c | awk '{print $5}'`
current_date=`date +%d`
prev_date=`expr $current_date - 1`
date_diff=`expr $current_date - $filedate`
current_time=`date +%H%M`
time_diff=`expr $current_time - $filetimestamp`
if [[ ${#fileyear} -eq 4 ]] ; then
if [ $fileyear -ne $current_year ]  ; then
echo "File is not of year $current_year"
exit
elif [ $filemonth != $current_month ] ; then
echo "File is of year $current_year but not $current_month month"
exit
fi
elif [ $filemonth != $current_month ] ; then
echo "File is of year $current_year but not $current_month month"
exit
fi
 
if [ $filedate -eq $prev_date ] || [ $filedate -eq $current_date ]; then
if [ $filedate -eq $current_date ]; then
echo "File was last updated on $filedate $filemonth $current_year at $filetime"
elif [ $filedate -eq $prev_date ] ; then
if [ $time_diff -le 0 ] ; then
echo "File was last updated on $filedate $filemonth $current_year at $filetime"
else
echo "File was updated on $filedate $filemonth $fileyear but before 24 hours from now"
fi
fi
else
echo "File was updated before $prev_date $current_month $current_year"
fi

Cheers
Harish

Thanks