Home > Blockchain >  Bash comparisson check to accept values only with format 0.1
Bash comparisson check to accept values only with format 0.1

Time:11-28

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related