Git Shell Tools

Although i work in a nice and fancy IDE with all bells and whistles i ever need. I still do a lot of my day to day work in a shell. One of those things is working with Git.

To make git more fun to work with on the command-line. There are a couple of things i did.

Let’s start with auto-complete. It’s great to be able to tab complete branch names, remote files and tree and file paths. To make this happen we only need to download the following bash script from the people at Github.

$ cd ~/bin
$ wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash

And to make this work in your shell add this to your .bashrc or .bash_profile

$ vi .bash_profile
git-completion
if [ -f ~/bin/git-completion.bash ]; then
    source ~/bin/git-completion.bash
fi

The only thing we need to do to make TAB completion work is reload the bash profile. We can do this by sourcing the file.

$ source ~/.bash_profile

Another fancy addition to working with git in a shell environment is something my coworkers showed me. It’s called the git-prompt. And is also created by the people at Github.

This script will do a couple of things. One of them is displaying which the current working branch is. More visible enhancements are possible by populating certain variables.

GIT_PS1_SHOWDIRTYSTATE Use the ‘*’ and ‘+’ characters to display unstaged and staged changes

GIT_PS1_SHOWSTASHSTATE Use ‘$’ to display stashed changes

GIT_PS1_SHOWUNTRACKEDFILES Will use ‘%’ to display there are untracked files

And more settings are possible. Check the readme at the beginning of the script for this. But what the script actually does is use the shells PS1 variable to display previously mentioned visible enhancements.

So let’s start by fetching the actual script

$ cd ~/bin
$ wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

Now that we have the script in place. Lets update the bash profile

git-prompt
if [ -f ~/bin/git-prompt.sh ]; then
   source ~/bin/git-prompt.sh
   GIT_PS1_SHOWDIRTYSTATE=true
   GIT_PS1_SHOWCOLORHINTS=true
   GIT_PS1_UNTRACKEDFILES=true
   export PS1='\[\e[31;1m\]\u\[\e[0m\]\[\e[37;1m\]@\[\e[0m\]\[\e[36;1m\]\h\[\e[0m\]$(__git_ps1 " \[\e[32;1m\][%s]\[\e[0m\]") \[\e[37;1m\]$\[\e[0m\] ' 
fi

In this case my PS1 is a bit more fancy because of the added colors. But the magic comes from adding

__git_ps1
$(__git_ps1 "[%s]")

When the profile is sourced once again. You can see what happens when we move to a repository

$ cd path/to/git/repository
PS1
username@hostname [branch-name *] $

The scripts used in this post can be found in this repository https://github.com/git/git/tree/master/contrib/completion

comments powered by Disqus