2

I have these branches:

refs/heads/master
refs/heads/feature/dummy

Is there native git command to get only the last part of branch name? (master, dummy in the above example)

I have tried git rev-parse --abbrev-ref HEAD but will get master and feature/dummy

12
  • 2
    There is no branch named dummy in the list you posted. The name of the second branch is feature/dummy. Git cannot identify it if you use only dummy. Try to run git checkout dummy and it will fail. Commented May 17, 2018 at 9:00
  • The branch you are currently on is feature/dummy Commented May 17, 2018 at 9:00
  • @axiac, @evolutionxbox yes, I know I am on feature/dummy. What I want is a git command to get dummy, not feature/dummy. This is because I have further processing that will not work with the forward slash Commented May 17, 2018 at 9:01
  • 1
    @evolutionxbox I have a analysis on SonarQube which will automatically strip the feature/ part of the branchname. I'll then have some code to hit Sonar's API to get analysis result, I'll need to pass in the short branchname as a param. But yeah, I can try grep or tokenize, I just want to know if there is a native git command Commented May 17, 2018 at 9:09
  • 1
    How about git rev-parse --abbrev-ref HEAD | xargs basename? Commented May 17, 2018 at 9:12

2 Answers 2

2

I think there isn't one, simply because git allows forward slashes in branch names. Take a look at git-branch docs to see how the branchname is defined: enter image description here Further more, take a look at the git-check-ref-format docs to understand how can you restrict this, if need be (--allow-onelevel).

With all that in mind, I think git sees the branch name as a whole, including the slash, so it wouldn't need to provide any specific command to parse it, but you can always pipe the branch name to another tool that will filter it out. For example this SO answer addresses such case. You would probably have to use something like: value=${str#*/}.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I think I will need to pipe or tokenize the branch name to get the last part
2

The following also seems to work:

$ git name-rev --name-only refs/heads/master
master

This appears to be very similar to the rev-parse solution you proposed yourself. It also appears to work on hashes, e.g. where b51e7569 is the commit pointed to by master:

$ git name-rev --name-only b51e7569
master

1 Comment

Thanks git name-rev --name-only HEAD did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.