Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check an input string in bash it's in version format (n1.n2.n3)

Tags:

regex

bash

sed

I've written an script that updates a version on a certain file. I need to check that the input for the user is in version format so I don't finish adding number that are not needed in those important files. The way I have done it is by adding a new value version_check which where I delete my regex pattern and then an if check.

version=$1
version_checked=$(echo $version | sed -e '/[0-9]\+\.[0-9]\+\.[0-9]/d')

if [[ -z $version_checked ]]; then
    echo "$version is the right format"
else
    echo "$version_checked is not  in the right format, please use XX.XX.XX format (ie: 4.15.3)"
    exit
fi

That works fine for XX.XX and XX.XX.XX but it also allows XX.XX.XX.XX and XX.XX.XX.XX.XX etc.. so if user makes a mistake it will input wrong data on the file. How can I get the sed regex to ONLY allow 3 pairs of numbers separated by a dot?

like image 311
Llanos Avatar asked Oct 09 '22 16:10

Llanos


1 Answers

Change your regex from:

/[0-9]\+\.[0-9]\+\.[0-9]/

to this:

/^[0-9]*\.[0-9]*\.[0-9]*$/
like image 103
anubhava Avatar answered Oct 13 '22 09:10

anubhava