2

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
0

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The part where you explain about each part of the Regex is really helpful for newbies like myself!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.