Git search for string in a single file's history

Git

Git Problem Overview


So if I have a file called foo.rb and it is giving me an error for a missing method called bar, so I want to search the history of foo.rb for the string bar to see if it was ever defined in the past.

I found this https://stackoverflow.com/questions/4468361/search-all-of-git-history-for-string

But this searches all files. I just want to search in one file.

Git Solutions


Solution 1 - Git

For this purpose you can use the -S option to git log:

git log -S'bar' -- foo.rb

Solution 2 - Git

Or maybe you can try this one (from related questions Search all of git history for string)

git rev-list --all foo.rb | (
    while read revision; do
        git grep -F 'bar' $revision foo.rb
    done
)

It will actually look for file content and not commit messages/patches for any occurence of bar.

Solution 3 - Git

I used git log -S "string" --follow -p "path of file" which shows the full history of all changes with that string.

Solution 4 - Git

There's an override for git log command (from manual):

$ git log Makefile      # commits that modify Makefile

So you could use:

git log foo.rb | grep "bar"

Solution 5 - Git

As mentioned by @Jakub Narębski I prefer to regex search for diff that contains 'bar'

git log -G'bar' -- foo.rb

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJD IsaacksView Question on Stackoverflow
Solution 1 - GitralphtheninjaView Answer on Stackoverflow
Solution 2 - GitAntoine PelisseView Answer on Stackoverflow
Solution 3 - Gitstack questionsView Answer on Stackoverflow
Solution 4 - GitDmitry ReznikView Answer on Stackoverflow
Solution 5 - GitMustapha-BelkacimView Answer on Stackoverflow