Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
    
Make sure to include whole bash prompt in double quotes. If you put it in single quotes, the value inside parenthesis won't evaluate. – superjisan Mar 11 '14 at 5:40
1  
@user3173748 If you want something in the prompt to be evaluated on usage time, it has to be single quoted or at least escaped or it will be evaluated on definition. That aside, there isn't even anything in the question to be evaluated as it just shows, how the prompt should look like and not how it is defined. – Adaephon Mar 11 '14 at 7:26
up vote 25 down vote accepted

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?

share|improve this answer
    
Is it possible to avoid the brackets and change the color? – Cedric Reichenbach Jun 18 '13 at 15:33
1  
@CedricReichenbach yes, to avoid brackets you just rewrite the PS1 line (without the brackets). For color see here: tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html – hayd Sep 11 '13 at 23:24
    
Well, I rewrote the parse_git_branch method like that: git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/|\1/' and added color in PS1 like in your linked tutorial. – Cedric Reichenbach Sep 12 '13 at 7:24
    
There needs to be a correction to this answer to include the fact that it will display branch if and only if your current directory is a repository. See my post : askubuntu.com/a/766060/295286 – Serg May 1 at 20:36

Add this one liner to the .bashrc:

export PS1='\u@\h \W$(__git_ps1 " [ - %s - ]") \$ '
share|improve this answer

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

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\`__git_ps1`\$ '
share|improve this answer
    
And what is __git_ps1? – muru Feb 12 at 19:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.