我正在嘗試在 AIX (ksh/bash) 中創建一個腳本,我需要將兩個變數與兩種不同的日期格式進行比較,并在 StartTime 和 CurrentTime 之間的差異大于 5 分鐘時發出警報。
例如,如果我有一個包含這三個變數的腳本:
StartTime="20 Oct 2022 12:20:48 -0700"
CurrentTime=$(date)
AlertThreshold=300
如果 StartTime 和 CurrentTime 之間的差異大于 AlertThreshold(300 秒),我該如何比較兩者,并做些什么?
$(date) 回傳的值采用以下格式:Thu Oct 20 12:37:05 PDT 2022
我一直試圖找出一種方法將兩個變數轉換為可以比較值的格式,以便我可以測驗時間差是否大于 AlertThreshold。
我假設兩者都需要轉換為unix時間戳來比較?
任何幫助,將不勝感激。
日期命令用法:
[mmddHHMM[[cc]yy]] [ "Field Descriptors"]
Usage: date [-n][-u] [mmddHHMM[.SS[cc]yy]] [ "Field Descriptors"]
Usage: date [-a [ |-]sss[.fff]]
uj5u.com熱心網友回復:
你不能用perl嗎?
if perl -MDate::Parse -e '
exit( str2time($ARGV[1]) - str2time($ARGV[0]) <= $ARGV[2] )
' "$StartTime" "$CurrentTime" "$AlertThreshold"
then
echo alert
fi
uj5u.com熱心網友回復:
這應該做你想要的。關鍵是用來date把日期轉換成秒,剩下的就簡單了。如果您不需要人類可讀的時間,您可以使用,例如,CurrentTime="$(date %s)"并在幾秒鐘內專門作業。
#!/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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521134.html
標籤:重击壳克什
