Bash regex to match semantic version

I have the following:

versionNumber=$(sw_vers -productVersion) # Finds version number versionShort=${versionNumber:0:4} # Cut string to 1 decimal place for calculation 

which works when versions look like this:

 10.9.2 10.9.5 

but he will not match

 10.10.3 

since he will only return

 10.1 

but I want versionShort to be set to

 10.10 

I want to match the major version, the first point and the minor version, as described above.

+7
bash regex semantic-versioning
source share
3 answers

The continuous solution is to cut off the last point and everything that follows it:

 versionShort=${versionNumber%.*} 
+10
source share

I had a similar question, but I needed access to all 3 segments. I did some research and testing, and I found this to work well.

 product_version=$(sw_vers -productVersion) semver=( ${product_version//./ } ) major="${semver[0]}" minor="${semver[1]}" patch="${semver[2]}" echo "${major}.${minor}.${patch}" 

To answer this question directly, you could

 product_version=$(sw_vers -productVersion) semver=( ${product_version//./ } ) major="${semver[0]}" minor="${semver[1]}" patch="${semver[2]}" versionShort="${major}.${minor}" 

or you can use fewer variables

 product_version=$(sw_vers -productVersion) semver=( ${product_version//./ } ) versionShort="${semver[0]}.${semver[1]}" 
+4
source share

Regexp solution:

 [[ $versionNumber =~ ^[0-9]+\.[0-9]+ ]] && echo "${BASH_REMATCH[0]}" 

It always prints the first two numbers, for example, all:

 10.5 10.5.9 10.5.8.2 

Result 10.5 . You can also add an else clause to check if something is wrong (no match found).

Here is the longer version:

 if [[ $versionNumber =~ ^[0-9]+\.[0-9]+ ]]; then versionShort=${BASH_REMATCH[0]} else echo "Something is wrong with your version" >&2 fi 
+2
source share

All Articles