How to sort semantic versions in bash? How to sort semantic versions in bash? bash bash

How to sort semantic versions in bash?


Well, we could trick sort -V by adding a dummy character at the end of the string for lines that do not contain a hyphen:

$ echo "$versions" | sed '/-/!{s/$/_/}' | sort -V | sed 's/_$//'v1.4.0-alphav1.4.0-alpha1v1.4.0-patchv1.4.0-patch2v1.4.0-patch9v1.4.0-patch10v1.4.0v1.5.0-alphav1.5.0-alpha1v1.5.0-alpha2v1.5.0-patchv1.5.0-patch1v1.5.0

Underscore lexically sorts after hyphen. That's the trick.


You can use Linux sort:

$ printf "1.0\n2.0\n2.12\n2.10\n1.2\n1.10" | sort -t "." -k1,1n -k2,2n -k3,3n1.01.21.102.02.102.12

Source: https://gist.github.com/loisaidasam/b1e6879f3deb495c22cc#gistcomment-1613531


1. Custom script in bash

I implemented my own solution

The code a bit ugly, but it works.

Installation

$ curl -Ls https://gist.github.com/andkirby/0046df5cad44f86b670a102b7c8b7ba7/raw/version_sort_install.sh | bashSemantic version sort: /usr/bin/semversort$ semversort 1.0 1.0-rc 1.0-patch 1.0-alpha1.0-alpha1.0-rc1.01.0-patch

2. Using semver in node

NOTE: All versions must follow the particular schema and it DOESN'T support "patch".

https://github.com/npm/node-semver/blob/master/README.md

$ npm install --global semverC:\Users\u.user\.node\semver -> C:\Users\u.user\.node\node_modules\semver\bin\semversemver@5.3.0 C:\Users\u.user\.node\node_modules\semver$ ~/.node/semver 1.2.3 1.3.6-patch 1.3.6-beta 1.3.6 1.3.6-alpha 1.0.41.0.41.2.31.3.6-alpha1.3.6-beta1.3.6-patch1.3.6

3. Using PHP and version_compare() in console

Also, the PHP native version_compare() (with using PHP of course :)) here.