user3310334
user3310334

Reputation:

fastest possible way to get name of current branch, or an appropriate string if not on a branch

At the moment I use

git branch | grep \* | cut -d ' ' -f2-

But it's too slow in terms of execution time.

Is there a faster way to generate the same output?

And I mean identical output (I haven't seen any cases I dislike), e.g. detached heads

(HEAD detached at SHA)

rebasing

(no branch, rebasing BRANCH)

etc.


I already tried e.g.

cat .git/HEAD | cut -d '/' -f3

but I know that sometimes, e.g. if rebasing, that won't work. Then I would have to check for existence of .git/REBASE_HEAD ? Also there's the problem of locating the .git directory from any subdirectory. In the end I don't know if a solution like this would be faster, at least probably not if I (with my inexperience) am the one to code it.

Upvotes: 3

Views: 711

Answers (4)

Iago Carvalho
Iago Carvalho

Reputation: 410

You also can use git symbolic-ref. However, be careful, since this doesn't work when rebasing.

git symbolic-ref --short HEAD

By the way, this is the shorter command I know to get this information (29 chars)

Upvotes: 3

Romain Valeri
Romain Valeri

Reputation: 21998

You can also use git rev-parse : (but unfortunately, as for other answers, this does not handle the case of an in-process rebase)

git rev-parse --abbrev-ref HEAD

Both rev-parse and symbolic-ref are plumbing commands, probably very close in terms of execution time.

Upvotes: 2

Harish Ganesan
Harish Ganesan

Reputation: 135

Unless you have to absolutely use git commands, You can just read the branch name from the actual .git folder.

cat .git/HEAD | cut -d '/' -f3

This breaks, when you are not in any branch ( So does others ), during which it will return the SHA of the commit that you are in ( unlike the others ). I can't think of any other situation, where it may break.

Upvotes: 2

EncryptedWatermelon
EncryptedWatermelon

Reputation: 5598

I'm surprised it's that slow but you can try this. Might be equally slow.
git status|head -n1|cut -d ' ' -f4

Upvotes: 0

Related Questions