Coding_Rabbit
Coding_Rabbit

Reputation: 1337

How to compare time strings in Bash script?

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

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 296039

A string comparison, like you were already doing, works fine for this purpose when your date string format is well-chosen.

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

...properly emits as output:

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

Sudosu0
Sudosu0

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

Kent
Kent

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

Related Questions