Search the contents of a git repository with git grep

Bonnie Eisenman
InstructorBonnie Eisenman

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

Learn to use git grep to only search through the tracked files in a git repo. This is especially useful when you want to exclude build artifacts or locally installed dependencies, such as webpack bundles or the node_modules directory. You'll also note that git grep is automatically colorized - we'll see how to get the same coloring effect with grep --color.

[00:01] Let's go into the examples directory of TodoMVC and install the dependencies. If we do a recursive grep here for a common phrase, say like bind, which of course, we're writing JavaScript, so there's going to be a lot of instances of this.

[00:13] What we're going to see is that a lot of these results aren't actually relevant to us. They're not from files that we're tracking, or concerned about, they're just installed dependencies.

[00:22] Now, we're working in a git repository, which means that the files we actually care about are probably tracked in version control. We can use git grep to only search for the files that we actually care about, and git grep is invoked just like this.

[00:33] Then, we type our query string, which in this case is bind, and git grep bind ignores all the file in our git ignore, it only looks at what's tracked by git, and you can see now instead of all that junk with lots of node modules files, we're getting actual code from within this project.

[00:50] This differs from using plain grep in a lot of other ways too. For one thing, you'll notice that the results are highlighted in red. We can replicate that if we want to by adding the --color flag when we use grip.

[01:01] If I were to type grep -r --color bind, and search this current directory, while we still get a bunch of junk, we can at least get the same color results, which are really nice, especially when you're looking at a lot of results.

[01:12] In addition to the match highlighting, you'll also see that we're using left to view these results, which when you're looking in a large directory, also makes things much more manageable.

[01:21] Git grep is often faster than normal grep, because it's leveraging the existing git index of your directory, which is really nice, and it provides these nice sort of convenience functions on top of regular behavior of grep, without requiring you to pass all these extra flags.

[01:34] One note of caution, if you're not seeing results that you would expect to see when usually searching with grep, make sure to check the gitignore files in your directory to make sure you're not missing something, just because it's being ignored by git.