Search code examples
regexbash

Regex for positive integer or an asterisk


I'm trying to write a bash script that would accept an interger parameter or an asterisk for all days of the month - ideally this should be limited to 1-31 as well.:

if [[ ! $DAY_OF_MONTH =~ ^[0-9]|*+$ ]]; then
  echo "ERROR: DAY_OF_MONTH parameter must be a positive integer or an asterisk"
  exit 1
fi

However, it keeps failing and I see the error message on the output.


Solution

  • You can group the 2 alternatives, escape the asterix (and use a single occurrence if that is in the error message) and make the pattern for possible days in a month more specific.

    if [[ ! $DAY_OF_MONTH =~ ^((0?[1-9]|[1-2][0-9]|3[0-1])|\*)$ ]]; then
      echo "ERROR: DAY_OF_MONTH parameter must be a positive integer or an asterisk"
      exit 1
    fi