Git: Show the first tag containing a commit SHA
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:
Output
<tag>~<n>
when the given commit is<n>
commits before the<tag>
.Output
<tag>^0
when the given commit is the one with tag<tag>
.Fail if the commit does not appear in any tags, such as:
$ git describe --contains c4bad802022 fatal: cannot describe 'c4bad802022ece9818d7edee1f7b5a43ba8484fb'
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
...
Read my book Boost Your Git DX for many more Git lessons.
One summary email a week, no spam, I pinky promise.
Related posts:
- Git: Show and copy commit SHAs
- Git: Show commits that come after
- Git: Output just the current branch name
Tags: git