Skip to content

Instantly share code, notes, and snippets.

@srguiwiz
Forked from henrik/.bashrc
Last active January 27, 2024 22:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srguiwiz/de87bf6355717f0eede5 to your computer and use it in GitHub Desktop.
Save srguiwiz/de87bf6355717f0eede5 to your computer and use it in GitHub Desktop.
Git branch and dirty state in Bash prompt.
# http://henrik.nyh.se/2008/12/git-dirty-prompt
# http://www.simplisticcomplexity.com/2008/03/13/show-your-git-branch-name-in-your-prompt/
# username@Machine ~/dev/dir [master]$ # clean working directory green
# username@Machine ~/dev/dir [master*]$ # dirty working directory red*
#
function git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
# http://unix.stackexchange.com/questions/88307/escape-sequences-with-echo-e-in-different-shells
function markup_git_branch {
if [[ "x$1" = "x" ]]; then
echo -e "[$1]"
else
if [[ $(git status 2> /dev/null | tail -n1) = "nothing to commit, working directory clean" ]]; then
echo -e '\033[1;32m['"$1"']\033[0;30m'
else
echo -e '\033[1;31m['"$1"'*]\033[0;30m'
fi
fi
}
export PS1='\u@\h \[\033[0;34m\]\w\[\033[0m\] $(markup_git_branch $(git_branch))$ '
@srguiwiz
Copy link
Author

Color coded branch name depending on state. Green or red.

@jcgoble3
Copy link

So I took this and improved on it a bit. Check it out here: https://github.com/jcgoble3/gitstuff/blob/master/gitprompt.sh This uses more reliable code that doesn't rely on a specific output that could change in a new version of Git, and is a bit cleaner and easier to read. Feel free to use it or improve on it more.

@jsharpminor
Copy link

On my Win7 machine, it leaves my commands and their output as black on black if in a Git repository.

@muru
Copy link

muru commented Nov 20, 2016

There's should be a slight change to original code here: the \033[0;30m at the end should be \033[0;0m to reset the prompt colour. The former sets it black, the latter resets formatting on the text.

@omostan
Copy link

omostan commented Jan 27, 2024

Kudos to @srguiwiz for the original code and also to @jcgoble3 for imrpoving on it further.
I also made few changes to suite my need. I wanted to maintain the system color, show a different color (red) for master branch and white all other branches. If the status is "dirty", the font should become italic and blinking. With this little tweak, I had to folk @jcgoble3 code and can be found here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment