Modify promt to make it GIT specific.

24 / Sep / 2012 by Hitesh Bhatia 0 comments

We use git a lot, and one of the most used commands is “git branch”. Few Months back we found a script that enabled us to modify our prompt so that it shows our current branch. We have modified it further to add extra functionality, and our modified script enables prompt to show number of files modified, number untracked files, and also the new files along with the branch name.

Below is sample image from terminal.

In image the prompt shows same information briefly as shown by git status. Here

  1. U shows Untracked files.
  2. M shows modified files
  3. And NEW Shows new file that has been added to Git

And below is the actual script.

[shell]
GST="git status"
OLDPS1=$PS1

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

function git_status() {
if current_git_status=$($GST 2> /dev/null | grep ‘modified’); then
COUNT=`git status |grep "modified" | wc -l| sed -e ‘s/^[ \t]*//’`
echo "[M x $COUNT]"
fi
}

function git_untracked(){
if current_git_status=$($GST 2> /dev/null | grep ‘Untracked files:’ ); then
echo "[U]"
fi
}
function new_file_check(){
if git_dir=$(git branch 2> /dev/null | grep ‘*’ ); then
COUNTNEW=`git status | grep "new file:" | wc -l| sed -e ‘s/^[ \t]*//’`
if [ $COUNTNEW -gt 0 ]; then
echo "[New x $COUNTNEW]"
fi

fi
}

function ren_file_check(){
if git_dir=$(git branch 2> /dev/null | grep ‘*’ ); then
COUNTREN=`git status | grep "renamed:" | wc -l| sed -e ‘s/^[ \t]*//’`
if [ $COUNTREN -gt 0 ]; then
echo "[Renamed x $COUNTREN]"
fi

fi
}

function git_hash(){
if git_dir=$(git branch 2> /dev/null | grep ‘*’ ); then
echo "[`git log -1 –oneline | cut -d" " -f1 `]"
fi
}

function gitfyPrompt(){
if updatePrompt=$(git branch 2> /dev/null | grep ‘*’ ); then
echo " ###############################################"
echo " # Welcome to Git Console #"
echo " # Use restorePrompt to restore your prompt #"
echo " ###############################################"
PS1="\[\e[1;31m\]Git-Console \[\e[0m\] \W : \$(new_file_check)\$(ren_file_check)\$(git_status)\$(git_untracked)\$(parse_git_branch)$ "
else
echo "WORKS ONLY IN GIT REPO"
fi

}

function restorePrompt(){
echo " ###############################################"
echo " # Exiting Git Console #"
echo " ###############################################"

PS1=$OLDPS1
}

gitfyPrompt
[/shell]

This really saves tons of time and is pretty handy for a quick reference.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *