Bash – Issues with regex match using the =~ operator of the bash [[ command

bashdateosxregular expression

On OSX, I am building a function to validate date formats and then convert them to epoch times. The function should validate that the date is in one of the following formats, if not error: 01/01/1970 10:00PM or 10:00PM (%m/%d/%Y %I:%M%p or %I:%M%p)

FUNCTION

checkTIME () {
    local CONVERT_CHK_TIME="$1"
    if [[ "$CONVERT_CHK_TIME" =~ ^(0[0-9]|1[0-2]):[0-9][0-9](AM|PM)$ ]]; then
        CONVERT_TIME="$(date -j -f "%I:%M%p" "$CONVERT_CHK_TIME" "+%s")"
    elif [[ "$CONVERT_CHK_TIME" =~ (0[0-9]|1[0-2])\/([0-2][0-9]|3[0-1])\/\d{4}\s[0-9][0-9]:[0-9][0-9](AM|PM) ]]; then
        CONVERT_TIME="$(date -j -f "%m/%d/%Y %I:%M%p" "$CONVERT_CHK_TIME" "+%s")"
    else
        echo "ERROR!"
        exit 1
    fi
}

It currently works fine for 10:00PM but is failing to match when I try 01/10/2017 10:00PM

I'm calling it as follows:

./convert '01/10/2017 10:00PM'
...
...
+ [[ -n 01/10/2017 10:00PM ]]
+ checkTIME '01/10/2017 10:00PM'
+ local 'CONVERT_CHK_TIME=01/10/2017 10:00PM'
+ [[ 01/10/2017 10:00PM =~ ^(0[0-9]|1[0-2]):[0-9][0-9](AM|PM)$ ]]
+ [[ 01/10/2017 10:00PM =~ (0[0-9]|1[0-2])/([0-2][0-9]|3[0-1])/d{4}s[0-9][0-9]:[0-9][0-9](AM|PM) ]]
+ echo 'ERROR!'
ERROR!
+ exit 1

Thanks!

I've also tried the following regex:

(0[0-9]|1[0-2])\/([0-2][0-9]|3[0-1])\/\d{4}\ [0-9][0-9]:[0-9][0-9](AM|PM)

Best Answer

\d matches a decimal digit in some versions of regex (perl), but does not in the Extended Regular Expressions used for the =~ operator of the [[ command in bash.

Therefore, change the \d to [0-9] for a pattern that will match 4 decimal digits.

Similarly for \s. To match one literal space character, replace the \s with an escaped space (\). If you want to match 1 or more blanks (spaces or tabs) then replace the \s with [[:blank:]]+.

More importantly, to avoid these regex mix-ups:

man bash says that =~ regular expressions match according to the extended regular expression syntax, as documented in regex(3).
man 3 regex (POSIX regex functions) says SEE ALSO regex(7).
man 7 regex gives a description of the regular expression syntax, and says SEE ALSO POSIX.2, section 2.8 (Regular Expression Notation).

You can find the complete POSIX Extended Regular Expressions syntax described in The Open Group's Posix Regular Expressions documentation.

Related Question