Git: Show the first tag containing a commit SHA

Artist’s impression of a complex branching and tagging structure.

Say you have a commit SHA and want to know the first version it was released in. You can use this command:

$ git describe --contains <sha> | sed -E 's/[~^][0-9]*//g'

Replace <sha> with the commit SHA.

For example, I recently wanted to know which version of Django first contained commit 4555aa0, so I ran:

$ git describe --contains 4555aa0 | sed -E 's/[~^][0-9]*//g'
4.0a1

The pipeline first uses git describe to get a “description” for this commit, based upon containing tags:

$ git describe --contains 4555aa0
4.0a1~23

This command will either:

In the success cases, the sed command then strips the ~<n> or ^0 suffixes to leave just the tag name.

Add an alias

To make this command easier to run, add a Git alias for it. Add the following to your global configuration file (~/.git/config/git or ~/.gitconfig), merging with any existing [alias] section:

[alias]
    show-containing-tag = "!f() { git describe --contains \"$1\" | sed -E 's/[~^][0-9]*//g' ; }; f"

Then, run it like so:

$ git show-containing-tag 4555aa0
4.0a1

For more on how the alias works, refer to Boost Your Git DX.

List all containing tags

To list all tags that contain a given commit, use git tag with its --contains option:

$ git tag --sort=creatordate --contains 4555aa0
4.0a1
4.0b1
4.0rc1
4.0
4.0.1
...

Fin

Bag those tags,

—Adam


Read my book Boost Your Git DX for many more Git lessons.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: