Matthieu Napoli
Matthieu Napoli

Reputation: 49533

Determine if we checked out a branch or a tag with git

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?

Upvotes: 3

Views: 2558

Answers (4)

jthill
jthill

Reputation: 60245

(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.

Upvotes: 1

A.H.
A.H.

Reputation: 66223

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

Upvotes: 10

Matthieu Napoli
Matthieu Napoli

Reputation: 49533

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).

Upvotes: 0

Claudio
Claudio

Reputation: 10947

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.

Upvotes: 0

Related Questions