Bash comparison check to accept values only with format 0.1

94 views Asked by At

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.

2

There are 2 answers

0
Cyrus On BEST ANSWER

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

0
Hizoka On

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