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

1
  • 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 dates format string? What does not work (any errors)? Obviously -ge can only compare integers ... but you should still add this to the question.
    – pLumo
    Sep 23, 2021 at 6:16

2 Answers 2

0

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.

1
  • azureuser@puppetclient-ubuntu:~$ echo $current_time "1632388663" azureuser@puppetclient-ubuntu:~$ echo $sub_time 1632384000 else condition is getting executed why.?
    – Haridvpsk
    Sep 23, 2021 at 9:18
0
#!/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
3
  • Instead of filtering date output with awk, why not simply use date +%H:%M ?
    – pLumo
    Sep 23, 2021 at 6:46
  • after if condition get satisfied also my cron job is not created why?
    – Haridvpsk
    Sep 23, 2021 at 9:26
  • Thanks a lot Mr.PLumo & Mahek the both the answers works for me .
    – Haridvpsk
    Sep 23, 2021 at 14:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .