0

How to check if a string contains version in numberic/decimal format in shell script

for eg we have 1.2.3.5 or 2.3.5

What if we do not have a constraint on the number of characters we have in here. It could x.x.x.x or x.x as well.

3
  • 1
    A regular expression? Commented Jun 12, 2013 at 1:30
  • 1
    Do you care about -alpha versions, RC versions, -stable versions, etc? Commented Jun 12, 2013 at 1:30
  • Hope that your script doesn't contain IP addresses. Commented Jun 12, 2013 at 4:49

4 Answers 4

4

If you're using bash, you can use the =~ regex match binary operator, for example:

pax> if [[ 1.x20.3 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ; then echo yes ; fi

pax> if [[ 1.20.3 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ; then echo yes ; fi
yes

For your particular test data, the following regex will do the trick:

^[0-9]+(\.[0-9]+)*$

(a number followed by any quantity of .<number> extensions) although, if you want to handle edge cases like 1.2-rc7 or 4.5-special, you'll need something a little more complex.

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

Comments

3

Using bash regular expressions:

echo -n "Test: "
read i

if [[ $i =~ ^[0-9]+(\.[0-9]+){2,3}$ ]]; 
then
  echo Yes
fi

This accepts digits.digits.digits or digits.digits.digits.digits

Change {2,3} to shrink or enlarge the acceptable number of .digits (or {2,} for "at least 2")

  • ^ means beginning of string
  • [0-9]+ means at least one digit
  • \. is a dot
  • (...){2,3} accepts 2 or 3 of what's inside the ()
  • $ means end of string

2 Comments

You could use {2,} to remove the upper bound: 1.2.3.4.5.6.7.8
@glennjackman Thanks. Re the question, it seems to be 3 or 4 numbers, but, indeed, that could be at least 2 (+1, the first)
0

And if you're truly restricted to the Bourne shell, then use expr:

if expr 1.2.3.4.5 : '^[0-9][.0-9]*[0-9]$' > /dev/null; then
  echo "yep, it's a version number"
fi

I'm sure there are solutions involving awk or sed, but this will do.

1 Comment

Actually, this would accept "1..2", which might not be acceptable to you.
-2

Flip the logic: check if it contains an "invalid" character:

$ str=1.2.3.4.5; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup
$ str=123x4.5;   [[ $str == *[^0-9.]* ]] && echo nope || echo yup
nope

Downside to this answer:

$ str=123....; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup

Comments

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.