21

How can I configure the terminal to display the current git branch?

I'd like to see the second line rather than the first:

andy@bob:~/my_projects/project_x$ 
(master)~/my_projects/project_x$

I don't want to have to run git status to see which branch I am currently on anymore!

muru
  • 207,228
hayd
  • 2,397

4 Answers4

34

You can add the following code to you .bashrc file:

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

You can move around these component parts to configure to your tastes, for example to prepend $(parse_git_branch) and not show the user@computer part I used:

PS1="\$(parse_git_branch)${debian_chroot:+($debian_chroot)}\w$ "

Which displays:

(master)~/my_projects/project_x$ 

See also: What is this PS1 variable doing in .bash_profile file?

Eliah Kagan
  • 119,640
hayd
  • 2,397
-1

Add this one liner to the .bashrc:

export PS1='\u@\h \W$(__git_ps1 " [ - %s - ]") \$ '
Eric Carvalho
  • 55,453
Vipin Verma
  • 5,524
  • 15
  • 45
  • 64
-1

You can also add the following line to your .bashrc:

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\`__git_ps1`\$ '
-2

This will add color to the branch name in terminal

git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[1;31m\]'"\$(git_branch)\[\033[00m\]$ "