How to test if variable is in specified format in Bash?

Viewed 109

My Bash script accepts an argument of a version number, in the following format: #.#.#.#.dev or #.#.#.#.prod, where # can be any number, for example: 3.6.212.0.dev.

I want to verify that the argument is in the right format (contains all the 4 numbers separated by dots and includes .prod or .dev in the end).

I'm not sure how to achieve this, so far I've tried this:

re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
echo "error: Incorrect version specified; must be in the format of #.#.#.#.env" >&2; exit 1
fi
1 Answers

You can use

re='^([0-9]+\.){4}(dev|prod)$'
if ! [[ "$1" =~ $re ]] ; then
  echo "error: Incorrect version specified; must be in the format of #.#.#.#.env" >&2; exit 1
fi

See a Bash demo online.

^([0-9]+\.){4}(dev|prod)$ is a POSIX ERE compliant pattern that matches:

  • ^ - start of string
  • ([0-9]+\.){4} - four occurrences of one or more digits and a dot
  • (dev|prod) - dev or prod substring
  • $ - end of string.
Related