Saturday, September 30, 2023
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 3104  / 1 Year ago, sun, april 17, 2022, 11:38:04
#!/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.



More From » bash

 Answers
7

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.


[#1162] Sunday, April 17, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rinstracte

Total Points: 221
Total Questions: 114
Total Answers: 120

Location: France
Member since Fri, Jan 28, 2022
2 Years ago
rinstracte questions
Wed, Jun 15, 22, 02:09, 1 Year ago
Tue, Jan 24, 23, 01:39, 9 Months ago
Wed, Jun 9, 21, 04:34, 2 Years ago
Sun, Oct 3, 21, 08:14, 2 Years ago
;