James Raitsev
James Raitsev

Reputation: 96381

How to modify shell to show git branch one is in, if applicable

Right now, my shell is set to display export PS1="\t \w $ "

Is there any way make prompt dynamic, always reevaluating it's current location and format to the following rules:

1. When inside directory that contains git repo, it changes to include branch i am on

19:42:07 (dev) ~ $ 

19:42:07 (release) ~ $ 

1.1 Can branch be shown in different color then the rest of the prompt?

2. When outside of the directory that contains git repo, it stays as is

19:42:07 ~ $ 

Upvotes: 1

Views: 101

Answers (2)

thameera
thameera

Reputation: 9473

In case the git-completion.bash solution isn't feasible (eg: no privileges to install git-completion, etc), you can manually add the following function to the .bashrc,

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

and call that function from the command to format PS1. I use the following:

PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h: \[\e[33m\]\w\[\e[37m\]$(parse_git_branch)\[\e[32m\] \$\[\e[0m\] '

which results in

enter image description here

where ParVal is the name of the branch I'm in.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992757

The Git distribution contains a contrib/completion/git-completion.bash file which does this, and much more besides. The file itself contains installation instructions.

Upvotes: 2

Related Questions