Git Tip of the Day – git grep

This will be a quick tip. Sometimes you need to search for something in your code, right? So you probably use:

$ grep -r 'foo()' /project

But unfortunately that may also print out results from files you didn’t want to search in, like backup files, compiled files (eg. build/ or dist/ directory, .pyc files for Python scripts,…), various temporary files, etc.

The solution is simple:

$ git grep 'foo()'

And voila! you searched only in the tracked files that are in your working tree. It ignores all files you don’t track (everything you have in .gitignore and anything you don’t track yet). What a beauty.

It behaves same as grep (performs recursion by default), supports same options and also adds a few git-specific ones.


Flattr this

4 thoughts on “Git Tip of the Day – git grep

  1. Unfortunately git has no “git find” command. You can create your alias own that behave fairly similar to the GNU find:

    find = !git ls-tree -r –name-only HEAD | grep –color $1

  2. You could also use ack[0] instead of grep, which automatically ignores known VCS files, and also supports restricting searches to source code in a particular language with simple command-line options.

    Can”t recommend it highly enough


    1. I tried ack and by default it does not search with suffix-less files (like README), you have to enable it. That is a pretty poor behavior, I can’t just rely on such tool. I know I can configure it, but hell, I can configure even grep. The reason I looked at it was because I was looking for a tool that “just works”. But it was not the case. (I also had some other issues, but I don’t remember now).

Leave a Reply (Markdown syntax supported)

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s