Skip to content
Git Today I Learned

Sort Git Tags by Ascending and Descending Semver

2 min read

Semver is a popular way of versioning applications and software libraries. However, if you use git tag to list out all your tagged versions of a Git repository you’ll probably find the tags returned are not listed in the expected order. That’s because by default Git uses lexicographic order, also known as dictionary or alphabetical order. Therefore, 1.10.0 will come before 1.2.0 when listing the tags in ascending order:

git tag
1.1.0
1.10.0
1.2.0
1.3.0
1.4.0
1.5.0
1.6.0
1.7.0
1.8.0
1.9.0

In semver, 1.10.0 is a higher version than 1.2.0.

Thankfully, Git provides us with a way of correctly sorting the returned tags by the version number. We can do this by using the option --sort v:refname:

git tag --sort v:refname
1.1.0
1.2.0
1.3.0
1.4.0
1.5.0
1.6.0
1.7.0
1.8.0
1.9.0
1.10.0

This is a lot better. We can also switch the direction of the listed tags so that the newest version comes first by prepending a - (dash):

git tag --sort=-v:refname
1.10.0
1.9.0
1.8.0
1.7.0
1.6.0
1.5.0
1.4.0
1.3.0
1.2.0
1.1.0

This is super useful if you’re trying to determine what version you want to tag next as you can quickly see the last version used.

Setting the default sort order

If like me you always use semver with your projects, you might want to make v:refname the default sort order. We can do this by setting the tag.sort config value for Git:

git config --global tag.sort v:refname

This means we just need to use git tag to get the tags listed in ascending semver order without the need for the sort flag. If you’d prefer the reverse order to be the default (newest version first) just prepend the value with a dash:

git config --global tag.sort -v:refname

If at any time you want to sort by lexicographic order again you just need to use the refname sort type:

git tag --sort refname
© 2024 Andy Carter