時刻Xを求める方法は、他の時刻Y及びZ以上である。

時刻Xを求める方法は、他の時刻Y及びZ以上である。

3回しよう

time1=11:34:45

time2:12:39:32

target_time:12:45:48

それでは、目標時間がtime1またはtime2以上であるかどうかはどうすればわかりますか?

希望の出力:

the target time 12:45:48 is greater or equal to 12:39:32

ベストアンサー1

まず、時間を比較しやすい一般形式(例:秒)に変換できます。

これは以下のbash関数で行うことができます。

time_to_seconds() {
    IFS=: read -r hours minutes seconds <<< "$1"
    echo $(( hours * 3600 + minutes * 60 + seconds ))
}

IFS=:時、分、秒を読み取るために文字列をコロンで区切るように bash に指示しますread

その後、次のように時間変数を秒に変換できます。

time1_secs=$(time_to_seconds "$time1")
time2_secs=$(time_to_seconds "$time2")
target_time_secs=$(time_to_seconds "$target_time")

まあ、ちょうどやるだけの問題比較する、このように:

if [ $target_time_secs -ge $time2_secs ]; then
    echo "the target time $target_time is greater or equal to $time2"
fi

おすすめ記事