How to find the Git commit that introduced a string in any branch?

Jonas Byström picture Jonas Byström · Apr 28, 2011 · Viewed 97.3k times · Source

I want to be able to find a certain string which was introduced in any commit in any branch, how can I do that? I found something (that I modified for Win32), but git whatchanged doesn't seem to be looking into the different branches (ignore the py3k chunk, it's just a msys/win line feed fix)

git whatchanged -- <file> | \
grep "^commit " | \
python -c "exec(\"import sys,msvcrt,os\nmsvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\nfor l in sys.stdin: print(l.split()[1])\")" | \
xargs -i% git show origin % -- <file>

It doesn't really matter if your solution is slow.

Answer

Mark Longair picture Mark Longair · Apr 28, 2011

You can do:

git log -S <whatever> --source --all

To find all commits that added or removed the fixed string whatever. The --all parameter means to start from every branch and --source means to show which of those branches led to finding that commit. It's often useful to add -p to show the patches that each of those commits would introduce as well.

Versions of git since 1.7.4 also have a similar -G option, which takes a regular expression. This actually has different (and rather more obvious) semantics, explained in this blog post from Junio Hamano.

As thameera points out in the comments, you need to put quotes around the search term if it contains spaces or other special characters, for example:

git log -S 'hello world' --source --all
git log -S "dude, where's my car?" --source --all

Here's an example using -G to find occurrences of function foo() {:

git log -G "^(\s)*function foo[(][)](\s)*{$" --source --all