Score:-1

How to compare time in if condition?

us flag
#!/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.

pLumo avatar
in flag
What are you trying to do? What is subtime? Why 17:00+1 = 16:00? Why do you use `awk` to filter output of `date` instead of using `date`s format string? What does not work (any errors)? Obviously `-ge` can only compare integers ... but you should still add this to the question.
Score:1
in flag

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.

Haridvpsk avatar
us flag
azureuser@puppetclient-ubuntu:~$ echo $current_time "1632388663" azureuser@puppetclient-ubuntu:~$ echo $sub_time 1632384000 else condition is getting executed why.?
Score:0
li flag
#!/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 substr($5,0,5)}')#output: 05:51
# on my system the 5th field has the time while the 4th field has the year.
# so I changed that in awk
if [[ "$sub_time" > "$current_time" ]];then # comparison done lexicographically
   crontab  <<EOF
   */15 * * * *  bash server_shutdown.sh
EOF
fi
pLumo avatar
in flag
Instead of filtering `date` output with `awk`, why not simply use `date +%H:%M` ?
Haridvpsk avatar
us flag
after if condition get satisfied also my cron job is not created why?
Haridvpsk avatar
us flag
Thanks a lot Mr.PLumo & Mahek the both the answers works for me .
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.