Is there any way to compare such strings on bash, e.g.: 2.4.5
and 2.8
and 2.4.5.1
?
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- JQ: Select when attribute value exists in a bash a
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
I implemented yet another comparator function. This one had two specific requirements: (i) I didn't want the function to fail by using
return 1
butecho
instead; (ii) as we're retrieving versions from a git repository version "1.0" should be bigger than "1.0.2", meaning that "1.0" comes from trunk.Feel free to comment and suggest improvements.
Here's a refinement of the top answer (Dennis's) that is more concise and uses a different return value scheme to make it easy to implement <= and >= with a single comparison. It also compares everything after the first character not in [0-9.] lexicographically, so 1.0rc1 < 1.0rc2.
GNU sort has an option for it:
gives:
Here is a simple Bash function that uses no external commands. It works for version strings that have up to three numeric parts in them - less than 3 is fine as well. It can easily be extended for more. It implements
=
,<
,<=
,>
,>=
, and!=
conditions.Here is the test:
A subset of the test output:
I'm using embedded Linux (Yocto) with BusyBox. BusyBox
sort
doesn't have a-V
option (but BusyBoxexpr match
can do regular expressions). So I needed a Bash version compare which worked with that constraint.I've made the following (similar to Dennis Williamson's answer) to compare using a "natural sort" type of algorithm. It splits the string into numeric parts and non-numeric parts; it compares the numeric parts numerically (so
10
is greater than9
), and compares the non-numeric parts as a plain ASCII comparison.It can compare more complicated version numbers such as
1.2-r3
versus1.2-r4
1.2rc3
versus1.2r4
Note that it doesn't return the same result for some of the corner-cases in Dennis Williamson's answer. In particular:
But those are corner cases, and I think the results are still reasonable.
Here is another pure bash solution without any external calls:
And there is even more simple solution, if you are sure that the versions in question do not contain leading zeros after the first dot:
This will work for something like 1.2.3 vs 1.3.1 vs 0.9.7, but won't work with 1.2.3 vs 1.2.3.0 or 1.01.1 vs 1.1.1