How to simulate "sort -V" on macOS

bash, git, gnu, macos, sorting

Solution

You can use additional features of `git tag` to get a list of tags matching a pattern and sorted properly for version tag ordering (typically no leading zeros):

$ git tag --sort v:refname
v0.0.0
v0.0.1
v0.0.2
v0.0.3
v0.0.4
v0.0.5
v0.0.6
v0.0.7
v0.0.8
v0.0.9
v0.0.10
v0.0.11
v0.0.12

From `$ man git-tag`:

   --sort=<type>
       Sort in a specific order. Supported type is "refname
       (lexicographic order), "version:refname" or "v:refname" 
       (tag names are treated as versions). Prepend "-" to reverse 
       sort order. When this option is not given, the sort order
       defaults to the value configured for the tag.sort variable
       if it exists, or lexicographic order otherwise. See 
       git config(1).

Problem

I have written a bash script that I need to work identically on linux and macOS that relies on the `sort` command. I am piping the output of `git tag -l` to `sort`, to get a list of all the version tags in the correct semantic order. GNU offers `-V` which makes this automagic but macOS does not support this argument, so I need to figure out how to accomplish this sort order without it. ``` 6.3.1.1 6.3.1.10 6.3.1.11 6.3.1.2 6.3.1.3 ... ``` needs to be sorted as ``` 6.3.1.1 6.3.1.2 6.3.1.3 ... 6.3.1.10 6.3.1.11 ```

Original source