Reputation: 1337
I want to compare two time strings in bash script. For example, 09:00:00 should be greater than 06:00:00. I wrote some code like this:
if [[ $1 > $time_higherbound ]]
echo "$1 > $time_higherbound"
fi
It turns out this approach does not work and I can get some example outputs like this:
09:00:01 > 09:00:00
09:00:01 > 10:00:00
09:00:01 > 24:00:00
09:00:01 > 17:00:00
09:00:01 > 24:00:00
Since I don't want the comparison include the date, I cannot use the comparison between timestamp. Does anybody know how to deal with this?
Upvotes: 0
Views: 4821
Reputation: 296039
Observe:
fixed_time=09:00:01
compare_times=(
09:00:00
10:00:00
24:00:00
17:00:00
24:00:00
)
for compare_time in "${compare_times[@]}"; do
if [[ $compare_time = $fixed_time ]]; then
echo "$compare_time = $fixed_time"
elif [[ $compare_time < $fixed_time ]]; then
echo "$compare_time < $fixed_time"
elif [[ $compare_time > $fixed_time ]]; then
echo "$compare_time > $fixed_time"
fi
done
09:00:00 < 09:00:01
10:00:00 > 09:00:01
24:00:00 > 09:00:01
17:00:00 > 09:00:01
24:00:00 > 09:00:01
Upvotes: 2
Reputation: 157
You will need to convert the date into seconds and compare that.
date1="$(date -d "$1" +%s)"
date2"$(date -d "$time_higherbound" +%s)"
if [ $date1 -gt $date2 ]; then
echo "$date1 > $date2"
fi
You can also convert back to a typical date format
echo $(echo `date -d @$date1`)
echo $(echo `date -d @$date2`)
Upvotes: 0
Reputation: 195289
You can convert the string into date to compare, or make use of awk
to do the comparison:
kent$ cat f
09:00:01 > 09:00:00
09:00:01 > 10:00:00
09:00:01 > 24:00:00
09:00:01 > 17:00:00
09:00:01 > 24:00:00
kent$ awk -F ' > ' '{print $0 " " ( $1>$2? "Yes":"No")}' f
09:00:01 > 09:00:00 Yes
09:00:01 > 10:00:00 No
09:00:01 > 24:00:00 No
09:00:01 > 17:00:00 No
09:00:01 > 24:00:00 No
You can do a comparison by checking the returned value:
awk -v a="$t1" -v b="$t2" 'BEGIN{print ($1>=$2?"1":"0")}'
Upvotes: 0