Jon
Jon

Reputation: 198

Compare two version numbers (true if different minor version)

I have to compare two version numbers (e. g. 5.6.2 and 5.7.0) in bash. But the function only has to return true if it is a higher or lower minor release number.

Examples:

| Old Version | New Version | return  |
| ----------- | ----------- | ------- |
|   5.6.2     |   5.7.0     |  true   |
|   5.6.2     |   5.6.9     |  false  |
|   5.6.2     |   5.6.9     |  false  |
|   5.6.2     |   5.5.0     |  true   |
|   5.6.2     |   5.8.8     |  true   |
|   5.6.2     |   6.0.0     |  true   |
|   5.6.2     |   4.0.0     |  true   |

Can anyone help me with this? I've tried to edit the function from BASH comparing version numbers but I couldn't get it run correctly.

Upvotes: 0

Views: 626

Answers (1)

CWLiu
CWLiu

Reputation: 4043

awk may help for this case. Here's a simple script to do that,

#!/bin/bash

old_version="$1"
new_version="$2"

awk -v u=${old_version} -v v=${new_version} '
BEGIN{ 
  split(u,a,"."); 
  split(v,b,"."); 
  printf "old:%s new:%s => ",u,v; 
  for(i=1;i<=2;i++) if(b[i]!=a[i]){print "true";exit} 
  print "false"
}'

The script would only compare major and minor version number, return false if they're matched, else return true.

Upvotes: 1

Related Questions