flk
flk

Reputation: 231

How to get previous tag name?

There are some tags:

first
second
third
fourth

I need to get the tag before "second" (third).

Upvotes: 20

Views: 19548

Answers (5)

aragaer
aragaer

Reputation: 17858

git describe --tags --abbrev=0 second^

Upvotes: 43

Udayendu
Udayendu

Reputation: 505

Following command also can be used:

git tag --sort=-creatordate | head -n 3 | tail -n 2

Upvotes: 1

tbot729
tbot729

Reputation: 61

I found out the hard way that the accepted answer to this question only finds tags reachable from the commit history for the branch you are on (which is fine for many use-cases).

I needed to get prior commit regardless of current branch history, so this solution worked more wholistically.

git for-each-ref --sort=-creatordate --format '%(refname:short)' refs/tags | sed -n '/second/{n;p;}'

Upvotes: 3

frost-nzcr4
frost-nzcr4

Reputation: 1620

Alternative solution with any sorting you like to get the next tag after the current one:

git tag --sort=-creatordate | grep -A 1 second | tail -n 1
  1. git tag --sort=-creatordate prints all tags from newest to oldest by creator date: "first second third fourth". Choose sorting option wisely.
  2. grep -A 1 second filter only "second" and one following line after it, i.e "third".
  3. tail -n 1 prints one last line from "second third" and we have finally get the "third".

Upvotes: 2

Gugelhupf
Gugelhupf

Reputation: 970

Or between the last two tags

git log $(git describe --abbrev=0 --tags $(git describe --abbrev=0)^)...$(git describe --abbrev=0) 

Upvotes: 9

Related Questions