git grep does is printing lines matching a pattern, it looks through the files tracked in the repo’s HEAD for lines matching a given pattern, and prints them.
If we look at it’s man page we see that the command has a huge number of options, here’s some that I find useful.
The simplest way to use it is
git grep foo, which will print all the lines in all the tracked files where
Sometimes the results list can be very dense, to improve readability we can use the
--break option, that will print an empty line between the matches form different files,
git grep --break foo.
Or maybe we’d like to look inside the matching files. We can make
git grep open the matching files in a “pager”, like
vim, to explore it’s content using
git grep -O foo.
We can restring the search scope to a path appending it, like this:
git grep foo -- a/path/.
git grep is even more powerful, it supports Boolean expression to combine patterns, so we can do cool things like
git grep -e foo --and -e bar or
git grep -e foo --and --not -e baz. Noticed the
-e? It means that the next parameter is a pattern, and it’s required when using these operators.
-e is also useful when the pattern you want to use starts with a dash
-, so that
git grep doesn’t read it as an argument.
And all this is just the tip of the iceberg! Have a look at
git grep --help or
man git-grep to find out more.
Food for thought
- Look into other useful options.
- What are the most surprising combo that can be made git
- Real example of usages of the command that helped solved problems during development.