Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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. –  user3173748 Mar 11 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 at 7:26

1 Answer 1

up vote 12 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

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.