Search code examples
gitgit-diffpre-commit-hookgit-index

Show files that are in Git's index and changed in the working copy


I have a Git pre-commit hook which strips whitespace and leaves the modified files in the working copy, so that it doesn't stomp on a partial add like git add -p.

If I commit one file out of many changed, and whitespace is corrected, I then have two files changed in the working copy and one staged file (which is also in the working copy, but the staged change has whitespace errors):

vi fileWithBadWS.txt  # leave bad whitespace
vi fileWithGoodWS.txt # don't leave bad whitespace
vi unrelatedFile.txt

git add fileWithBadWS.txt fileWithGoodWS.txt 
git commit -m "Commited files, one with bad whitespace" # pre-commit hook fails

The repo now looks like this:

On branch master
Changes to be committed:

        modified:   fileWithBadWS.txt  # bad WS
        modified:   fileWithGoodWS.txt

Changes not staged for commit:

        modified:   fileWithBadWS.txt   # fixed WS
        modified:   unrelatedFile.txt                                 

I can use:

  • git diff to see fileWithBadWS.txt and unrelatedFile.txt
  • git diff --cached to see staged files fileWithBadWS.txt and fileWithGoodWS.

How can I see only the files that are both modified in the working copy and staged (i.e. just fileWithBadWS.txt)?

Note: this question uses whitespace and pre-commit hooks as an example, but applies more generally to any situation when you have some files staged and some not, with some overlap.


Solution

  • How about this ?

    git diff --name-only --staged | xargs git diff --name-only

    This would show you files which are staged as well as changed in the working tree.