3

In a script, I would like to determine if a tag or a branch was checked out.

For now, I have:

git describe --tags 

It will show the tag name, but if we are on a branch, it will raise an error (with return status != 0):

fatal: No names found, cannot describe anything. 

Can I rely on this behavior or is there a better/more official way to do so?

Are there some cases that are not caught by this method that I should know?

2
  • I am on a branch and git describe --tags doesn't throw any error. It just shows the first reachable tag from where you are Commented May 30, 2013 at 14:30
  • @iberbeu Yes I noticed that, git describe --tags is not good for this, see my own answer ^^ Commented May 30, 2013 at 14:33

4 Answers 4

10

You can use git symbolic-ref HEAD to check if you are on a branch and get its name:

> git checkout master [....] > git symbolic-ref HEAD refs/heads/master > echo $? 0 

If you have checked out a tag you will get an error:

> git checkout some_tag [....] > git symbolic-ref HEAD fatal: ref HEAD is not a symbolic ref > echo $? 128 
Sign up to request clarification or add additional context in comments.

Comments

1

(edit) better than what I had earlier:

if read what where huh; test "$what" = ref: then echo On branch ${where#refs/heads/} else echo "not on any branch; last checkout was:" git reflog|sed '/checkout:/!d;q' fi < "`git rev-parse --git-dir`"/HEAD 

will tell you where your last checkout came from.

git log HEAD^! --oneline --decorate 

will tell you all the symbolic names for your current commit.

Comments

0

git status (or git branch) to know on which branch you are. Note: you're always on a branch: the default branch is master.

Use git tag to know the list of tags on the current branch.

2 Comments

When I am on a tag, git branch will show that I'm on * (no-branch) so I guess I'm not always on a branch? Also git tag is not very helpful to know on which tag I am (i.e. which tag I checked out).
(I replied posting another answer)
0

Well after some testing around, it turns out git describe --tags wasn't very reliable (in one case I had checked out a branch it did return something).

I ended up using:

git branch | grep '^*' 

This will return the selected branch. In case I checked out a tag, this will return:

* (no branch) 

In my script I parse the string to check if it contains (no branch).

1 Comment

and what if you are on a branch and on a tag at a time? In that case git tells you that you are not on a branch, while you actually are

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.