I have a piece of code in another than my current branch in my git repo, and I am not sure which commit and which branch. How can I search in all files that I committed until now for a specific string (and afterwards show the surrounding of that line of code)?
4 Answers
Use git grep to locate the commit:
git grep "string" $(git rev-list --all)
The git rev-list --all makes it search the entire history of the project.
That will give an output like this:
<commit>:<path>:<matched line>
Then you can use git branch --contains to find out which branch the commit is on:
git branch --contains <commit>
4 Comments
Yo Ludke
Can I specify to search in only one file/path? (E.g. I am searching for a specific fixture and only want to search in this path)
John Szakmeister
Yes:
git grep "string" $(git rev-list --all) -- path.tback
this doesn't work for big histories :(
git grep 'abc' echo $(git rev-list --all) zsh: argument list too long: gitHeath Borders
If you get
Argument list too long, you can use git rev-list --all | xargs git grep 'abc': stackoverflow.com/a/49243541/9636If the git grep "string" variation above is giving you "list too long" errors, you can use git log -S instead. The -S option searches the contents of the files that were committed:
git log -S "string" # look for string in every file of every commit
git log -S "string" -- path/to/file # only look at the history of the named file
(More in the "Pro Git" book under "searching".)
Comments
If jszakmeister's answer gives you an Argument list too long response:
$ git grep "string" $(git rev-list --all)
-bash: /usr/local/bin/git: Argument list too long
You can pipe it into xargs instead:
$ git rev-list --all | xargs git grep "string"
5 Comments
prem30488
How to escape this command after it is done?
Heath Borders
What do you mean by
escape this command?Koops128
Anyway to avoid
xargs: git: terminated by signal 11 ?Old Skull
@HeathBorders, what would be the right syntax for
git grep "string" -- '*.txt'? This command alone works as expected, but with piping it returns nothing.Heath Borders
You'd have to research how to use
xargs to inject arguments at specific places, or find out how git-grep behaves with --. I suspect your issue is that xargs expects commands to read from stdin, and maybe that doesn't happen when you use --.