Archive for the ‘Introductions’ Category

Unix prompt (PS1) with git branch name

Monday, July 14th, 2008

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:

  1. 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
    
  2. 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$ ”
    
  3. 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

colored_branch_name

First Post

Monday, June 25th, 2007

Welcome to Furmanek.net. This is my first post in a while, so I will keep it short. I am intending to write much more content and discuss wide variety of subjects starting with technology (my favorite) through politics, religions, philosophy, psychology and some other lighter stuff. I hope you will enjoy my writing and visit my site often.

You are currently browsing the archives for the Introductions category.

Social Networking

Gregory Furmanek's Facebook profile
View Gregory Furmanek's profile on LinkedIn