Check if a file was changed in a bash script

I’m using letsencrypt for most of my servers. One of these servers is behind a firewall without any direct internet connection. Therefore I’m not able to use letsencrypt or dehydrated directly on that server. I’m copying the certificate to a specific location as a normal ssh user and on that host itself I have to check if the certificate was changed to reload the webserver. I’ve solved that problem with a short shell script and the pretty cool unix tool called stat.

If you call that program with -c %Y you get the unixtime of last data modification. This timtestamp we can now compare with date +%s and check if tit was changed.

My script looks like the following code example:

#!/bin/bash

FILENAME="/PATH/TO/FILE"
# timediff in seconds. 120 == 2 min
OLDTIME=120
CURTIME=$(date +%s)
FILETIME=$(stat $FILENAME -c %>)
TIMEDIFF=$(expr $CURTIME - $FILETIME)

if [ $TIMEDIFF -lt $OLDTIME ];then
    # DO YOUR STUFF
fi

if you want to check if the file was not changed within the last 2 min you have to change -lt to -gt.

#!/bin/bash
if [ $TIMEDIFF -lt $OLDTIME ];then
    # DO YOUR STUFF
fi
comments powered by Disqus