0

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
3
  • What is the format of the times that you have in the variables? The same HH:MM:SS or something else?
    – Jeff Schaller
    Commented May 24, 2018 at 15:40
  • @Jeff Schaller same like HH:MM:SS
    – its_me
    Commented May 24, 2018 at 15:40
  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you!
    – Jeff Schaller
    Commented May 27, 2018 at 12:33

2 Answers 2

5

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.

2
  • I want to compare with <= operate . Kindly help me for this.
    – its_me
    Commented May 25, 2018 at 9:08
  • That’s not what you wrote originally; you said “time1=HH:...”. Perhaps you could open a new question that asks what you really want.
    – Jeff Schaller
    Commented May 25, 2018 at 9:20
3

If the format is the same, just compare them like any other string:

$ [ "$time1" = "$time2" ] && echo "match" || echo "no match"
2
  • I want to compare with <= operate . Kindly help me for this
    – its_me
    Commented May 25, 2018 at 9:06
  • That is different from the question originally posed. Please edit your question to ask what you actually want, and the answers will likely be modified to suit.
    – DopeGhoti
    Commented May 25, 2018 at 15:34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.