Find git commits related to a certain part of a file

Quite often I find myself staring at some old code that doesn’t look right. It looks like something has been removed (e.g. it has a loop that does nothing of value, or it creates a variable but doesn’t use it), or something is just hard to understand the point of. In these cases I would really need to see the history of that section of the file. Not all of the file though, just that section, or function.

Ideal solution
A simple command like

  • git log - line too long - no line break
  • How do I model a 'Central Library' in TFS 2010?
  • How can I translate trunk/branch concepts from Subversion to Git?
  • git-gui reports it has 256 loose objects each time is run and suggests compression which goes fine. How to fix it?
  • Working on git repo without cd into directory
  • git: how can i list new files to add them after?
  • git log books.cpp:10

    to find history of line 10 (possibly with surroundings) of file books.cpp is probably too much magic to ask for, but do you have ideas of how to work out that history?

    What I have tried
    I have tried using blame, and then checking out the commit before the given commit of that line – repeating it until I’ve seen enough. But that is very tedious work.

    Have you felt the need for this feature? Do you have a way of achieving it? Share your experience!

  • Understanding git gc --auto
  • Failed importing code from SVN to GIT - SVN trunk is empty
  • How can I disable diff in line separators in IntelliJ IDEA?
  • git create patch with diff
  • Correspondece between Git client and server versions
  • git lfs not working properly for files larger than 100MB
  • 2 Solutions collect form web for “Find git commits related to a certain part of a file”

    Git is very easy to extend. Does something like this achieve what you want?

    for hash in `git log --pretty=format:%h ${FILENAME}`
        echo "***************** Showing ${FILENAME} at ${hash}"
        git blame -L ${LINENUMBERS} ${hash} ${FILENAME}

    Put this little script in your path as something like git-linehistory and call it like this:

    git linehistory books.cpp 5,15

    It will show you what lines 5 to 15 look like at each commit for that file.

    • git blame -L option lets you specify a range of line to output, or even a regexp to match the function you want.
    • You can also specify to blame at a specific commit, then you don’t have to checkout the revision before the blame.

    So in short you can do successive calls to git blame -L range <commit> <file-name> to browse the history of line by line changes.

    Git Baby is a git and github fan, let's start git clone.