18

Is there a way to display last N tags in git?

I am not interested in a pattern because this can change. For example let's say I have these tags and I want to get last 3 of them:

v1.0.0
v1.0.1
v2.0.0
v2.1.0
v3.0.0

Based on the Pro Git seems that this cannot be achieved. Or I am missing something?

1

4 Answers 4

20

This can be done with git tag --sort option which is introduced in Git v 2.0.0.

Note: I'm using the minus sign - to get reverse sorting order (default is oldest to newest).

Replace <number> with an actual natural number.

UNIX, Linux, OS X

git tag --sort=-version:refname | head -n <number>

From man head:

 head [-n count | -c bytes] [file ...]

This filter displays the first count lines or bytes of each of the specified files, or of the standard input if no files are specified. If count is omitted it defaults to 10.

Windows, the UNIX way

  1. Install Cygwin
  2. See answer for UNIX

Windows, native way

git tag --sort=-version:refname | Select -First <number>

(Info on Select command was found on serverfault)

From git reference:

--sort=<type>

Sort in a specific order. Supported type is "refname" (lexicographic order), "version:refname" or "v:refname" (tag names are treated as versions). The "version:refname" sort order can also be affected by the "versionsort.prereleaseSuffix" configuration variable. 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.

6

There is no single command for this. You have to use a combination of the describe and rev-list commands for this.

git describe --tags $(git rev-list --tags --max-count=3)

Got the answer from here: https://stackoverflow.com/a/7979255/2336787

1
  • 1
    @nickvolynkin you are right. My answer is just an old alias that I have been using. I am still on msysgit 1.9.5 (which does not support the --sort option). So, I guess this answer is only for people still not on git 2.x
    – hsirah
    Jun 16, 2015 at 19:25
0

And on a remote repository (using Nick Volynkin's approach):

git ls-remote -tq --sort=-version:refname origin | egrep -v '\^\{}$' | head -n <number>
0

This can be done through:

Bash

git log --pretty='%(describe:tags=true,abbrev=0)' | uniq | head -n <N>

PowerShell

git log --pretty='%(describe:tags=true,abbrev=0)' | Get-Unique | Select -First <N>

Repleace <N> with the number you want.

Note: Though AC may be suitable in the real use case, it does not really target the question. It actually sorts the tags lexicographically but not chronologically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.