How to compare timestamp of a logfile and generate error in case its 72 hours old ?

Here in this article, we will look at a script created to check a logfile and if its older than 3 days i.e. 72 hours then send an email to us.

I. Script to achieve this task

[root@nglinux ~]# cat check_log.sh 
#!/bin/bash
LOGFILE="/root/testfile.txt"

### Get date and time before 3 days in seconds
t1=`date --date="3 days ago" +%s`

### Get modification date and time of the logfile
t2=`stat --format=%Y $LOGFILE`

let "gap=$t2-$t1"
let "hoursgap=$gap/3600"

##echo $gap $hoursgap

if [ $hoursgap -le 1 ]; then
	#### Send mail function
	echo "The file is older than 71 hours i.e. 3 days"
else
	echo "The file is created `echo $((72-$hoursgap))` hour ago."


fi
[root@nglinux ~]# 

 

II. Testing

[root@nglinux ~]# ./check_log.sh 
The file is created 1 hour ago.
[root@nglinux ~]# 

 

III. Debugging

[root@nglinux ~]# sh -x check_log.sh 
+ LOGFILE=/root/testfile.txt
++ date '--date=3 days ago' +%s
+ t1=1564828094
++ stat --format=%Y /root/testfile.txt
+ t2=1565083739
+ let gap=1565083739-1564828094
+ let hoursgap=255645/3600
+ '[' 71 -le 1 ']'
++ echo 1
+ echo 'The file is created 1 hour ago.'
The file is created 1 hour ago.
[root@nglinux ~]# 
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments