DEV Community

Easily get current branch name in git

kakty3 on July 06, 2017

Sometimes I miss the features from Mercurial which Git does not have. One of them is hg outgoing which "Show changesets not found in the specified ...
Collapse
 
lucasreeh profile image
Lucas Reeh • Edited

Thanks for the Info. I am using Oh my zsh based on zsh where you see the current branch directly in your prompt. It is very easy to install (it is a git repo itself with install script on github), so I even install it in some dev docker containers.

my favorite theme:
Agnoster theme

Collapse
 
andy profile image
Andy Zhao (he/him) • Edited

I'm tempted to use zsh with Oh my zsh (along with Vim), but haven't quite decided to switch over yet. My bash has something similar, where the branch is in the prompt:

bash branches

Collapse
 
lucasreeh profile image
Lucas Reeh • Edited

without trying to sound like a salesman ;) (it is open-source anyway): i foremost like the completion from history (works with spaces too). e.g. type: git commit + arrow up and you get all your recent commit commands. :)

Collapse
 
sabareeshk1991 profile image
Sabz

me too:)

Collapse
 
mgtitimoli profile image
Mauro Gabriel Titimoli • Edited

I was used to do the following

git branch | grep -e "^\*" | cut -d " " -f 2

This alternative, as it happens a lot with git, doesn't expose its purpuse clearly, but at least it provides a way to get the current branch, so I guess I will move to this approach instead.

Thanks for sharing!

Collapse
 
pratyaypandey profile image
Pratyay Pandey • Edited

If still you wish to use git branch without copy and paste you can probably try this

git branch | while read -r line ; do; if [[ ${line:0:1} == "*" ]]; then; echo $line | awk '{print $2}'; fi; done

Collapse
 
hawkinjs profile image
Josh Hawkins

While not a fancy one-liner or anything, I tend to just use git status to see "On branch ____" and just copy that as needed. Not great for scripting but easy to remember

Collapse
 
taylor profile image
Taylor D. Edmiston

This is what I do too. Or in Sublime using the Git plugin, activate the command palette then type "br" which jumps to "Git: Change Branch" with an asterisk next to the current branch.

Collapse
 
plutov profile image
Alex Pliutau

Alias for bash to show current branch in folder:

parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\w$(parse_git_branch)"