Bash script accepting variables in valid number format

Hi Experts
I would like to ask if there is a way to validate if the variable passed is in this kind of sample format "06-10" or "10-01". It was really a challenge to me on how to start and echnically the "6-10" stands for "June 10" and "10-01" stands as "October 1", overall it needs to have like of a "Month-Day" valid in number format. I would like to have an if-then statement that would validate if the variables passed are in correct, something like these:

#!/bin/bash 
# This script will ONLY accept two parameters in number format  
# according to "MM-DD" which is "XX-XX"  # To run this script: ./script.sh xx-xx xx-xx 
DATE1=$1 
DATE2=$2
 if [DATE1 is in correct format] && [DATE2 is in correct format]  
   then   
     echo "Correct format"   
     echo "DATE1 = $DATE1"   
     echo "DATE2 = $DATE2"  
   else   
     echo "Not correct format"    
    exit 1 
  fi

Welcome to the forum.

Very similar problems have been solved umpteen times in these forums. Did you use the search function, or have a look into the links at the bottom left under "More UNIX and Linux Forum Topics You Might Find Helpful"?

Date / time arithmetics is one of the worst tasks in IT, as many subtleties have to be covered / taken care of. It's not just checking we have two two-digit numbers separated by a dash. Certain months allow for certain days only. Do you need leap year dates considered?
You can use numerical comparisons, or string matching, for validations. What be your favorite?

No leap year tests here - would be impossible without knowing the year for each of the dates.

#!/bin/bash
MDAYS=(0 31 29 31 30 31 30 31 31 30 31 30 31)

function valid-mm-dd ()
{
     MONTH=${1%-*}
     DAY=${1#*-}
     MONTH=${MONTH#0}
     DAY=${DAY#0}

     [[ $MONTH =~ ^[0-9]{1,2}$ ]] || return
     [[ $DAY =~ ^[0-9]{1,2}$ ]] || return
     (( MONTH > 0 && MONTH < 13 )) || return
     (( DAY > 0 && DAY <= MDAYS[MONTH]))  || return
}
DATE1=$1
DATE2=$2

if valid-mm-dd $DATE1 && valid-mm-dd $DATE2
then
   echo "Correct format"
   echo "DATE1 = $DATE1"
   echo "DATE2 = $DATE2"
else
   echo "Not correct format"
   exit 1
fi
1 Like

@Chubler_XL - suggestion is the answer here:b: