0

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.

Jon
  • 188
  • 1
  • 9

1 Answers1

1

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.

CWLiu
  • 3,913
  • 1
  • 10
  • 14
  • Thank you for your answer. But your script doesn't work. I always get an syntax error: `syntax error near unexpected token `u,a,"."'` – Jon Jul 17 '18 at 08:36
  • Some lines in the script is not pasted successfully, I have corrected it. Please tried again. – CWLiu Jul 17 '18 at 08:48
  • @CWLiu, without speaking to anything else, you need more quotes: `-v u="$old_version" -v v="$new_version"`. Curly brackets do nothing meaningful for correctness here; quotes, by contrast, suppress word-splitting and glob expansion. – Charles Duffy Aug 31 '22 at 15:41