Friday, January 16, 2009

Bash: Calculate with file timestamp

Test if file is newer than yesterday 8 pm:
myfile:
myserver:/tmp # ll myfile
-rw-r--r-- 1 root root 0 Jan 16 09:47 myfile

Get timestamp of myfile:
myserver:/tmp # date -r myfile
Fri Jan 16 09:47:08 CET 2009


Get timestamp of myfile in seconds:
myserver:/tmp # date +%s -r myfile
1232095628

Yesterday 8 pm:
myserver:/tmp # date --date="`date +%F` -1 days + 20 hours"
Thu Jan 15 20:00:00 CET 2009

Yesterday 8 pm in seconds:
myserver:/tmp # date +%s --date="`date +%F` -1 days + 20 hours"
1232046000

Use BashCalc (bc) to compare the values:
pc2019:/tmp # echo "1232095628 > 1232046000" | bc
1
<-- return 1: file is newer than yesterday 8 pm

In a shellscript:
#!/bin/bash
TODAY=`date +%F`
YESTERDAY_8_PM_IN_SECONDS=`date +%s --date="$TODAY -1 days + 20 hours"`
echo "YESTERDAY_8_PM_IN_SECONDS:" $YESTERDAY_8_PM_IN_SECONDS

MYFILE="/tmp/myfile"
MYFILE_TIMESTAMP_IN_SECONDS=`date +%s -r $MYFILE`
echo "MYFILE_TIMESTAMP_IN_SECONDS:" $MYFILE_TIMESTAMP_IN_SECONDS

VAR=`echo "$MYFILE_TIMESTAMP_IN_SECONDS > $YESTERDAY_8_PM_IN_SECONDS" | bc`
echo "VAR:" $VAR

if test ${VAR} -eq 1
then
   echo "File $MYFILE is newer then yesterday 8 pm"
else
   echo "File $MYFILE is older then yesterday 8 pm"
fi


Script output:
myserver:/tmp # ./testmyfile.sh
YESTERDAY_8_PM_IN_SECONDS: 1232046000
MYFILE_TIMESTAMP_IN_SECONDS: 1232095628
VAR: 1
File /tmp/myfile is newer then yesterday 8 pm