git info in bash prompt

139 views
Skip to first unread message

Paul Wilson

unread,
Aug 22, 2012, 3:35:42 PM8/22/12
to hacker...@googlegroups.com
Hi all,

A few months ago, Anthony Scopatz shared his bash prompt that includes the current git branch when in a git-managed directory.

Today, I figured out how to make the color of that git branch change color depending on the status:
  • GREEN: if all previously tracked files are committed
  • YELLOW: if any files have been added but not committed, unless...
  • RED: if any file that has previously been tracked by git has been modified and not added

Shell snippets are below.

Paul


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

function get_git_color() {

    isred=`git status -s 2> /dev/null | egrep "^.[^? ]" | wc | awk '{print $1}'`
    isorange=`git status -s 2> /dev/null | egrep "^[^? ]" | wc | awk '{print $1}'`

    git_prompt_color=32

    if [ $isorange -ne 0 ]
    then
    git_prompt_color=33
    fi
    if [ $isred -ne 0 ]
    then
    git_prompt_color=31
    fi
   
    echo "$git_prompt_color"
}

# Guide to prompt:
#  * set the title bar to show the current time (\t) & current working directory (\w): "\[\e]0;\t \w\a\]"
#  * set the prompt to show:
#      * current user (\u) and host (\h) in green (\[\e[32m\]),
#      * working directory (\w) in yellow (\[\[e[33m\]): "\[\e[32m\]\u@\h \[\e[33m\]\w
#  * add the git branch name to the prompt: $(parse_git_branch)
#  * set color for git branch name based on status:
#     * all previously tracked files up-to-date/committed: green
#     * any previously tracked files NOT added: red
#     * some previously tracked files added but not committed: orange
export PS1="\[\e]0;\t \w\a\]\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[1;\$(get_git_color)m\] \$(parse_git_branch)\[\e[0m\]> "

-- 
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ --
Paul Wilson ~ UW-Madison ~ 608-263-0807 ~ cal: http://bit.ly/pphw-cal
Associate Professor, Engineering Physics. ~ http://cnerg.engr.wisc.edu
Chair, Energy Analysis & Policy Program ~ http://nelson.wisc.edu/eap

Anthony Scopatz

unread,
Aug 22, 2012, 3:56:48 PM8/22/12
to hacker...@googlegroups.com
Awesome!  Thanks Paul.

Mr. Puneet Kishor

unread,
Aug 22, 2012, 3:59:26 PM8/22/12
to hacker...@googlegroups.com

On Aug 22, 2012, at 12:35 PM, Paul Wilson <wil...@engr.wisc.edu> wrote:

> Hi all,
>
> A few months ago, Anthony Scopatz shared his bash prompt that includes the current git branch when in a git-managed directory.
>
> Today, I figured out how to make the color of that git branch change color depending on the status:
>
> * GREEN: if all previously tracked files are committed
> * YELLOW: if any files have been added but not committed, unless...
> * RED: if any file that has previously been tracked by git has been
And it works just as it says on the tin. Thanks Paul.


--
Puneet Kishor

Reply all
Reply to author
Forward
0 new messages