How to compare time in if condition?

#!/bin/bash
tag=$(awk -F, 'NR==1{print $1}' /tmp/time.txt)# output: 17:00
sub_time=$(date -d"${tag}  +1:00" +'%H:%M')output: 16:00
current_time=$(date |awk 'NR==1{print $4}' output: 05:51:16
if [[ "$sub_time" -ge "$current_time" ]];then
   crontab  <<EOF
   */15 * * * *  bash server_shutdown.sh
EOF
fi

I want to compare the "current_time" in the current system to the VM shutdown tag from VM with "sub_time" through the if condition.


It would be safer to convert the date strings to timestamps:

%s seconds since 1970-01-01 00:00:00 UTC

[[ $(date +%s -d "$sub_time") -ge $(date +%s -d "$current_time") ]]

Of course you could directly do this when creating the variables:

sub_time=$(date -d"${tag}  +1:00" +%s)
current_time=$(date +%s)
if [[ $subtime -ge $current_time ]]; then
   ...
fi

  • Instead of creating current_time by yourself, you could use the bash variable $EPOCHSECONDS (bash > 5.0).
  • You could also use printf instead of date to create it: printf -v current_time '%(%s)T'

Be aware that these options might not be very portable.