How to filter git diff based on file extensions?

Solution 1:

Yes, if you ensure that git expands a glob rather than your shell then it will match at any level so something like this (quotes are important) should work fine.

git diff -- '*.c' '*.h'

Solution 2:

To include files recursively (including current dir) this worked for me:

git diff -- '***.py'

Solution 3:

Either use your shell's globstar (which does a recursive search)1,2:

shopt -s globstar 
git diff -- *.py **/*.py

or use find:

find -name '*.py' -print0 | xargs -0 git diff --

Both of these are special-names and whitespace proof. Although you might want to filter for directories having the .py extension :)


1 I like to do git diff -- {.,**}/*.py usually

2 When globstar is enabled, git diff -- **/*.py already includes ./*.py. In Bash's manpage: 'If followed by a /, two adjacent *s will match only directories and subdirectories.'

Solution 4:

For simple file patterns, this seems to work:

$ git ls-files -zm '*.txt' | xargs --null git diff

Whitespace safe, and you can have multiple extensions too:

$ git ls-files -zm '*.h|*.c|*.cpp' | xargs --null git diff