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]]
CodePudding user response:
Can't you use perl
?
if perl -MDate::Parse -e '
exit( str2time($ARGV[1]) - str2time($ARGV[0]) <= $ARGV[2] )
' "$StartTime" "$CurrentTime" "$AlertThreshold"
then
echo alert
fi
CodePudding user response:
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