Unix prompt (PS1) with git branch name
Working with Git I noticed that I change branches quite a lot. This is a good thing but sometimes I am in the incorrect branch when I check things in. I needed a warning system especially when I check things into remote SVN repository. Since most of my check-ins are done from the command line it would be nice to know what branch I am on just by looking at the screen. Fortunately there is neat way to add the branch information to the Unix prompt. You can do that by overriding the PS1 variable for example:
export PS1="[\D{%Y-%m-%d} \t] \w \n$"
would generate
[2008-07-12 12:00:00] /foo/bar $
if I am in the /foo/bar directory.
So at this point I would like the prompt to look like:
[2008-07-12 12:00:00] /foo/bar [master]
$
when I am in a master branch and prompt:
[2008-07-12 12:00:00] /foo/bar [experimental]
$
when I am in any other branch.
Here are the steps to get this working:
Prerequisites:
- ruby interpreter
- git
Steps:
- Create a git-ps.rb file
green = "\033[0;32m" white = "\033[0;37m" red = "\033[0;31m" current_branch = `git branch 2>/dev/null`.grep(/^\*/).first if current_branch branch_name = current_branch.gsub(/^\*\s*/,'').strip color = branch_name =~ /master/ ? green : red unless current_branch.empty? puts " #{color}[#{branch_name}]#{white}" end end - create .ps file in your home directory:
parse_git_branch() { ruby ~/git-ps.rb 2>/dev/null } export PS1="[\D{%Y-%m-%d} \t] \w\$(parse_git_branch) \n$ " - Include the .ps file in your .bashrc and .bash_profile by inserting following line:
. ~/.ps
To activate the new prompt in your current execute command:
. ~/.ps
I hope this helps.
References
Ref: Prompt Creation
Ref: Git and Bash prompt
Ref: __git_ps1
Downloads
Social Networking