Reputation: 67
I am trying to create a script in AIX (ksh/bash) where I need to compare two variables with two different date formats, and raise an alert if the difference between the StartTime and CurrentTime is greater than 5 minutes.
As an example, if I have a script that has these three variables:
StartTime="20 Oct 2022 12:20:48 -0700"
CurrentTime=$(date)
AlertThreshold=300
How can I compare the two, and do something if the difference between StartTime and CurrentTime is greater than AlertThreshold (300 seconds)?
The value returned by $(date) is in this format: Thu Oct 20 12:37:05 PDT 2022
I am stuck trying to figure out a way to convert both variables to a format where I can compare the values, so that I can test to see if the time difference is greater than AlertThreshold.
I assume both would need to be converted to unix timestamp to compare?
Any help would be appreciated.
date command usage:
[mmddHHMM[[cc]yy]] [+"Field Descriptors"]
Usage: date [-n][-u] [mmddHHMM[.SS[cc]yy]] [+"Field Descriptors"]
Usage: date [-a [+|-]sss[.fff]]
Upvotes: 0
Views: 1104
Reputation: 17216
You could use perl
:
if perl -MDate::Parse -e '
exit( str2time($ARGV[1]) - str2time($ARGV[0]) <= $ARGV[2] )
' "$StartTime" "$CurrentTime" "$AlertThreshold"
then
echo alert
fi
Or a 100% portable way that you can adapt to your time formats; it shouldn't be too difficult as long as the timezones are the same for the two dates.
Upvotes: 1
Reputation: 48330
This should do what you want. The key is to use date
to convert the dates to seconds, and then the rest is straightforward. If you don't need the times to be human-readable, you can use, e.g., currentTime="$(date +%s)"
and work exclusively in seconds.
#!/bin/bash
startTime="20 Oct 2022 12:20:48 -0700"
currentTime="$(date)"
alertThreshold=300
# Convert dates to seconds.
currSec=$(date -d "${currentTime}" +%s)
startSec=$(date -d "${startTime}" +%s)
if ((currSec - startSec > alertThreshold)); then
echo "Alert!"
else
echo "Keep waiting."
fi
Upvotes: 1