How to use git effectively

  |   Source

To take the full power of git, you need forget GUI and use CLI only. A little knowledge of script language like Bash/Perl/Python may be helpful.

Here is an example how I use git.


I'm working for a big enterprise project which uses git as version control software. My daily routine is find what files I changed. So I often use git commands with "–stat" parameters.

git show --stat
git diff --cached --stat
git log --stat
git diff --stat

Since I use CLI git in bash shell only. I set alias for these commands in bash. For example, I need only type gds in bash instead of git diff --stat.

Git commands with "–stat" option usually only display relative paths, so I write some bash function which enable me select that relative path interactively (without using mouse, of course), convert that path to absolute path, and copy that absolute path into clipboard.

Getting full path into clipboard is useful because in big projects I need do lots of communication with managers and colleagues. For example, I need list files I changed in our bug tracking system (JIRA) and also email them using Outlook. If you still don't understand why it's hard in big project, let me give you some hint. Big project is usually a big shit. If you edit file A, you will find another 10 files distributed in different location with same file name and similar code. Those files are not your business.

Set up

Now you understand the problem. Here comes the solution.

Step 1, You need install percol by sudo pip install percol. Percol will provide some interactive UI to help you select the line in shell.

Step 2, install xclip under Linux to support paste text into X clipboard. BTW, you did install some clipboard manager under Linux, didn't you?

Step 3, insert below code into your ~/.bash:

# search the file and pop up dialog, then put the full path in clipboard

function pclip() {
    if [ $OS_NAME == CYGWIN ]; then
        putclip $@;
    elif [ $OS_NAME == Darwin ]; then
        pbcopy $@;
    elif [ -x /usr/bin/xclip ]; then
        xclip -selection c $@;
        echo "xclip is not installed!"

function glsf () {
    local str=`git --no-pager log --oneline --decorate --stat $* |percol`
    if [[ $str =~ ^[[:space:]]*([a-z0-9A-Z_.\/-]*).*$ ]]; then
        echo -n ${BASH_REMATCH[1]} |pclip;
        echo ${BASH_REMATCH[1]}

function ff()
    # @see
    local fullpath=$*
    local filename=${fullpath##*/}
    local filter=${fullpath##*./}
    #  only the filename without path is needed
    # filename should be reasonable
    local cli=`find $PWD -type f -iname '*'${filename}'*'|grep ${filter}|percol`
    echo ${cli}
    echo -n ${cli} |pclip;


ff line-from-clipboard
# now I can paste the full path into firefox, outlook ...

Here is the screen cast: git-find-full-path.gif

Comments powered by Disqus