In a git repository, is there any difference/benefit using git grep
over good old grep
?
An example would be?
The two are very similar. The main difference is that git grep
defaults to searching in the files that are tracked by git.
If I want to find foo
within my project I can use git grep
or good ol' stand-alone grep
:
git grep foo
grep -R foo .
The git grep
version will only search in files tracked by git, whereas the grep
version will search everything in the directory. So far so similar; either one could be better depending on what you want to achieve.
What if we want to limit the search to only .rb
files?
git grep foo -- *.rb
grep -R --include=*.rb foo .
The plain old grep
version is getting a bit more wordy, but if you're used to using grep
that may not be a problem. They're still not going to search exactly the same files, but again it depends on what you want to achieve.
What about searching in the previous version of the project?
git grep foo HEAD^
git checkout HEAD^; grep -R foo .; git checkout -
This is where git grep
makes a real difference: You can search in another revision of the project without checking it out first. This isn't a situation that comes up too often for me though; I usually want to search in the version of the project I have checked out.
There are some git config
variables that modify the behaviour of git grep
and avoid the need to pass a couple of command line arguments:
grep.lineNumber
: Always show line numbers of matches (you can pass -n
to both grep
and git grep
to get this behaviour)grep.extendedRegexp
: Always use extended regular expressions (you can pass -E
to both grep
and git grep
to get this behaviour)In practice I have gg
aliased to git grep -En
, and this almost always does what I want.