0
#!/bin/sh

REGEX="^[2][0-2]:[0-5][0-9]$"
TIME="21:30"

if [ $TIME = $REGEX ]; then
    echo "Worked"
else
    echo "Did not work"
fi

I guess it has something to do with the : but as far as I'm concerned, this is just a regular sign that needs no escape sequence.

Strict
  • 15

2 Answers2

3

The simple = is wrong for regexp comparison. You have to use =~, and you'll also have to use a doubled bracket:

if [[ $TIME =~ $REGEX ]]; then
  ...

See also: https://stackoverflow.com/questions/17420994/bash-regex-match-string

John
  • 17,011
1

You could also go for the case statement:

REGEX="[2][0-2]:[0-5][0-9]"; # Note no placeholders like ^ and $ here
TIME="21:30"
case $TIME in
   $REGEX ) echo "Worked" ;; # Note no double quotes around $REGEX for allowing the wildcard matching to happen
        * ) echo "Did not work" ;;
esac