0

I have this snippet:

if [[ $1 =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; then
     echo 'version is good'
     exit 0
else 
     exit 1
fi

The problem is that, the snippet $1 =~ ^[+-]?[0-9]+\.?[0-9]*$ should only validate versions formatted as number.number

Currently this chunk of code validates inputs as

1
01
0.1

Is there any way of making the code to only accept inputs formatted as 0.1 / 0.3.2 / 0.1.141 etc.

Thanks in advance.

EDIT:

To clarify this question, the code should only accept numbers separated with dots, like software program versioning.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • To be clear, do you want to only accept inputs with at least 2 groups of numbers separated by `.`? And are we accepting `+` and `-` signs in the input? That part of the regex seems irrelevant to this question. – rchome Nov 27 '21 at 00:55
  • You write "_should only validate versions formatted as `number.number`_" and then "_Is there any way of making the code to only accept inputs formatted as `0.1` / `0.3.2` / `0.1.141` etc._" This is contradictory. Please edit your question and clarify your specification. No comments, no images, no external links, just edit your question. Thanks. – Renaud Pacalet Nov 27 '21 at 08:05
  • Hi @RenaudPacalet @rchome sorry for my typos, what I would like to achieve is just to validate inputs passed as ``number.number.number`` It should only accept numbers separated between dots. – PythonicExperience Nov 27 '21 at 09:50

2 Answers2

2

I suggest this regex: ^[0-9]+(\.[0-9]+){1,2}$

Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

I propose without regex :

[[ "0" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # Nothing 
[[ "01" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # Nothing 
[[ "0.1" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK 
[[ "0.3.2" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK 
[[ "0.1.141" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "10.1.141" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK

To clarify this question, the code should only accept numbers separated with dots, like software program versioning.

[[ "0" == +([0-9]).+([0-9.]) ]] && echo OK # Nothing 
[[ "01" == +([0-9]).+([0-9.]) ]] && echo OK # Nothing 
[[ "0.1" == +([0-9]).+([0-9.]) ]] && echo OK # OK 
[[ "0.3.2" == +([0-9]).+([0-9.]) ]] && echo OK # OK 
[[ "0.1.141" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "10.1.141" == +([0-9]).+([0-9.]) ]] && echo OK # OK
Hizoka
  • 58
  • 6