0

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
1
  • 1
    Bash’s [[ knows regex. Or use grep. Commented May 24, 2018 at 12:05

2 Answers 2

0

The if-statement would look like this:

if [[ $DATE1 =~ ^[0-9]{1,2}-[0-9]{1,2}$ ]] && [[ $DATE2 =~ ^[0-9]{1,2}-[0-9]{1,2}$ ]]

It checks if the date has the string format ##-##.

Sign up to request clarification or add additional context in comments.

2 Comments

It would also validate 99-66 as a valid date, perhaps add range to the number?
@Kokogino - I replaced the "if" line but when I tried the script it still gives a valid "Correct Format". I tried passing "55-55 55-55" and "55-55 55-55 ab" but I got the incorrect response telling me it is in correct format
0

replacing the regex on the if statement worked by using this:

^(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.