Search code examples
regexbashif-statementdigitsalphabetical

Bash if statement to check for like 1 letter and 2 numbers


Need some help with a script. I am trying to make sure the user enters a valid school term, like F18, F19 etc.

The letters that can be used are F, S, M, N (which are Fall, Spring, Summer, Special) the numbers are years, 18, 19, 20, 21 etc.

The problem with my current setup if someone mistyped for example ff18, it's correct, or f181 it's correct. I want it to only accept 1 letter and 2 numbers.

#!/bin/bash

term_arg=$1
letter_range="[f|F|s|S|m|M|n|N]"
number_range="[10-99]"
if [[ "${term_arg}" = "" ]] || ! [[ "${term_arg}" =~ ${letter_range}${number_range} ]]; then
  echo "Please specify a valid term: e.g. F18, S19, M19, etc. "
  exit 1
else
  echo "The term id ${term_arg} is correct"
  exit 0
fi

Solution

  • Square brackets introduce character classes, so

    [f|F]
    

    matches any of the three characters: f, |, or F.

    Similarly,

    [10-99]
    

    matches 1, 0 to 9, and 9, which is equivalent to [0-9] or [0123456789].

    So, you need

    [fFsSmMnN][0-9][0-9]
    

    Note that this works with plain =, too, no need to use regular expressions, as the right hand side is interpreted as a pattern unless quoted:

    $ [[ m18 = [fsmn][0-9][0-9] ]] && echo matches
    matches