0

I have to read a epoch timestamp (in seconds) from a directory /usr/local/healthcheck.txt on my Red Hate Enterprise Linux machine every ~10 minutes (polling). I need perform a comparison on the time to check if the timestamp in the healthcheck.txt file is OLDER than 50 minutes from the current time/timestamp OR if the healthcheck.txt is non-existent, to throw an error. The timestamp in the healthcheck.txt file generally looks like this (its in seconds, as stated above) :

1591783065

I was using date -d @1591783065 to convert the timestamp to Human Readable and get something like this:

Tue Jun 9 16:22:57 UTC 2020

What would be the best approach to compare the current timestamp to this timestamp in the file and check if its older than 50 minutes?

In Java , we have a Date package , and can just use compareTo to compare the times/dates, is there a simple way to do this with shell/bash scripts?

ennth
  • 844
  • 6
  • 20

1 Answers1

4

Why don't you stick with epoch-time? You can get the current time as seconds since epoch by date +%s, so you just have to compare

if (( (healthcheck_time + 50*60) < $(date +%s) ))
then
  # .... healthcheck older than 50 minutes
fi
user1934428
  • 12,137
  • 4
  • 27
  • 62
  • 2
    In bash 5 and higher you can use the [built-in `$EPOCHSECONDS`](https://stackoverflow.com/a/54177664/6770384) instead of `$(date +%s)`. – Socowi Jun 10 '20 at 14:19
  • @user1934428 I could just subtract to get the TIME DIFFERENCE like this $(date +%s) - healthcheck_time, then convert to minutes and check if those MINUTES > 50 then // do some logic , right? – ennth Jun 10 '20 at 15:13
  • Sure, but why convert into minutes? In zsh, this might work (but is still unnecessary), but in bash arithmetic, you have only integers, and you would have to do rounding. Therefore I would stick with seconds. – user1934428 Jun 11 '20 at 06:10