bashsortingversionsemantic-versioning

How to sort semantic versions in bash?


I would like to sort semantic versions (semver.org)

v1.4.0
v1.4.0-alpha
v1.4.0-alpha1
v1.4.0-patch
v1.4.0-patch9
v1.4.0-patch10
v1.4.0-patch2
v1.5.0
v1.5.0-alpha
v1.5.0-alpha1
v1.5.0-alpha2
v1.5.0-patch
v1.5.0-patch1

in proper way. For instance, as version_compare() does in PHP (it doesn't directly, but can be used for that).

Of course, sort -V|--version-sort doesn't work here.

$ echo 1.0 1.0-alpha | tr ' ' "\n" | sort --version-sort
1.0
1.0-alpha

Is there some exist approach?

P.S.

In common sense, it should follow this schema:

1.0.0-alpha 
  < 1.0.0-alpha.1 
    < 1.0.0-alpha.beta 
      < 1.0.0-beta
        < 1.0.0-beta.2
          < 1.0.0-beta.11
           < 1.0.0-rc.1 < 1.0.0
             < 1.0.0-patch < 1.0.0-patch.1.

P.P.S.

Semver 2.0 doesn't support patches, but it's needed.


Solution

  • 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 | bash
    Semantic version sort: /usr/bin/semversort
    
    $ semversort 1.0 1.0-rc 1.0-patch 1.0-alpha
    1.0-alpha
    1.0-rc
    1.0
    1.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 semver
    C:\Users\u.user\.node\semver -> C:\Users\u.user\.node\node_modules\semver\bin\semver
    semver@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.4
    1.0.4
    1.2.3
    1.3.6-alpha
    1.3.6-beta
    1.3.6-patch
    1.3.6
    

    3. Using PHP and version_compare() in console

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