Sorting Git Tags in Semantic (Natural) Order

A lot of people use semantic versioningwith their git tags. Like this:

$ git tags
v0.1.3
v0.3.12
v1.5.0
v0.10.7

Getting the most recent version (or all of the versions in order) is a pain because sorting them doesn’t give the correct semantic order:

$ git tags | sort
v0.1.3
v0.10.7
v0.3.12
v1.5.0

The v0.10.7 mistakenly appears before the v0.3.12 because 1 < 3.

If your versions do not have the vprefix, you can simply use:

$ git tags | tr '.' ' ' | sort -k1,1 -k2,2 -k3,3 -n | tr ' ' '.'
0.1.3
0.3.12
0.10.7
1.5.0

However, if your versions do contain the vprefix (or any other prefix for that matter) you will have to strip it out before the sort, like:

$ git tags | tr '.' ' ' | tr -d 'v' | sort -k1,1 -k2,2 -k3,3 -n | tr ' ' '.' | xargs -I{} -n 1 echo "v{}”
v0.1.3
v0.3.12
v0.10.7
v1.5.0

Notice that the prefix is stripped off with tr, but then appended after the sortwith xargs.

Other Tips

  1. You can use heador tailto find the most recent or oldest versions respectively.
  2. Add -r to the sort command to get the versions in reverse.
  3. Use grepto filter the tags before performing the sort. This is helpful if you have other tags that are not versions or should not be included in the output.

Originally published at http://elliot.land on December 18, 2017.

Written by

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store