How can I find the most recent tag across all branches in a git repo?

Viewed 58

I'd like to know how can I find the most recent tag across all branches in a git repo.

I've tried using the following command, but this only appears to check on the current branch:

git describe --abbrev=0 --tags | sed 's/[^0-9.]*//g'

I'd like to check all branches however.

1 Answers

Here's a script in bash.

#!/bin/bash

#list all the tags 
git for-each-ref --shell refs/tags |
  awk '{
#transform the object name into the commit date as a Unix epoch timestamp 
    "git log -1 --pretty=%cd --date=unix "$1 | getline $1;
#if the tag does not refer to a commit, ignore it
    if($0 ~ /^[0-9a-f]/) print;
#sort by the timestamp reversely, from the youngest to the oldest
  }' | sort -r |
#get the first youngest tag
  head -1 | awk '{print $NF}' |
#get all the tags that point at this tag in case there are multiple youngest tags, 
#with a side effect to remove "refs/tags/"
  xargs -i git tag --points-at {}

One-line version:

git for-each-ref --shell refs/tags | awk '{"git log -1 --pretty=%cd --date=unix "$1 | getline $1;if($0 ~ /^[0-9a-f]/) print;}' | sort -r |head -1 | awk '{print $NF}' | xargs -i git tag --points-at {}

If you are using Git before v2.9.4, use --date=iso instead of --date=unix. With --date=iso there might be a bug that the timestamps can't be sorted as expected due to time zones. But I think it's rare to happen.

Related