0

So, I can't get the time format check in the following code to pass:

#!/usr/bin/env bash
#
date="$1"
time="$2"

if [[ $date =~ ^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$ ]]; then
   if [[ $time =~ ^(0[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9])\s([AaPp][Mm])$ ]]; then
      echo "Input Matched!"
   else
      echo "Invalid time! Use <HH:MM:SS AM/PM> format!"
      exit 1
   fi
else
   echo "Invalid date! Use <MMDD> format!"
   exit 1
fi

I have tried so many variations of the time check and nothing has worked. I think the problem is with the space check. I've tried the "[[:space]]" and "[[:blank]]" but those didn't work. Please help.

Also, I've researched this to death. I've tried so many searches and I've come up with nothing. If someone does find a question that solves my issue can you tell me the search you used?

  • Why don't use "date -d " command instead of writing script at all? date command can read data in several formats, for example: date -d "20/05 23:59", date -d "next tuesday", date -d "yesterday". – Saboteur Oct 04 '21 at 00:25
  • 1
    @Saboteur, why didn't I use "date"? Because I wasn't that smart :). – Justin Paro Oct 05 '21 at 22:08

1 Answers1

1

You need to

  • Use [[:space:]] or [[:blank:]] instead of \s
  • Use double quotes around the text variables.

Here is the working script:

#!/usr/bin/env bash
date="$1"
time="$2"

if [[ "$date" =~ ^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$ ]]; then
   if [[ "$time" =~ ^(0[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9])[[:space:]]([AaPp][Mm])$ ]]; then
      echo "Input Matched!"
   else
      echo "Invalid time! Use <HH:MM:SS AM/PM> format!"
      exit 1
   fi
else
   echo "Invalid date! Use <MMDD> format!"
   exit 1
fi
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563