I have two time variables. I want to compare it in if statement in shell script.
e.g.
time1=HH:MM:SS
and time2=HH:MM:SS
.
Format is HH:MM:SS
.
if [it matched]
then
echo "matched"
else
echo "not matched"
fi
I have two time variables. I want to compare it in if statement in shell script.
e.g.
time1=HH:MM:SS
and time2=HH:MM:SS
.
Format is HH:MM:SS
.
if [it matched]
then
echo "matched"
else
echo "not matched"
fi
If you want to compare the (contents of) two variables to a particular HH:MM:SS string, then just compare them to those strings and tie the tests together with a logical "and" (&&
):
if [ "$time1" = "01:23:45" ] && [ "$time2" = "01:42:42" ]
then
echo matched
else
echo not matched
fi
Another option is to use case
; it allows for some flexibility in matching the times, in case you don't want to match against a specific HH:MM:SS. To start with, let's tie the two times together with an implicit "and":
time1=01:23:45
time2=01:42:42
case "$time1,$time2" in
(01:23:45,01:42:42) echo yes;;
esac
Here I stubbed in a comma, just to help you the script-reader see what's going on; it could be omitted.
Now let's say that you don't care as much about time2's SS
portion:
case "$time1,$time2" in
(01:23:45,01:42:*) echo yes;;
esac
Or maybe you want time2's seconds to be in a certain range:
case "$time1,$time2" in
(01:23:45,01:42:4[1-3]) echo yes;;
esac
You can extend the examples from there.
If the format is the same, just compare them like any other string:
$ [ "$time1" = "$time2" ] && echo "match" || echo "no match"