27

When I want to get git diff files, I found someone use

git diff-index --cached  --diff-filter=AM --name-only  HEAD

and if I use

git diff --cached --diff-filter=AM --name-only  HEAD 

can get the same result. So what's the difference between git diff and git diff-index? When you must use git diff-index but not git diff?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
myyuanyuan5200
  • 293
  • 1
  • 3
  • 5

3 Answers3

18

git diff-index is a diff against the index or working tree:

Compares the content and mode of the blobs found in a tree object with the corresponding tracked files in the working tree, or with the corresponding paths in the index

git diff is more versatile and can compare two files, or two commits, or (like diff-index) a tree and the index.

In your case, a diff HEAD would indeed diff HEAD against the index, which diff-index does too.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 1
    what is the index? – Will Apr 15 '17 at 11:01
  • 5
    @Will the index is where you prepare your next commit. Linux Torvalds, when making Git back in 2005, needed a tool where he could add multiple changes while ignoring others, in order to prepare the next Linux code commit. For more: http://stackoverflow.com/a/4086986/6309 – VonC Apr 15 '17 at 11:44
  • git diff-index is not always against the index. As the documentation says: "Compare a tree to the working tree or index" – Droopycom May 03 '18 at 04:33
  • @Droopycom Agreed. I have edited the answer accordingly. – VonC May 03 '18 at 22:24
2

diff-index is a lower level operation that does less but is much faster because it doesn't look at the content, it only checks metadata like timestamps. Only Linux you can verify this with something like:

  strace -f -e file -o diff-index.log git diff-index HEAD
  wc diff-index.log
  less diff-index.log

Forget about diff-index unless you have some git performance problem to solve.

https://git-scm.com/docs/git-update-index#_using_assume_unchanged_bit

https://public-inbox.org/git/loom.20160331T143733-916@post.gmane.org/

MarcH
  • 18,738
  • 1
  • 30
  • 25
1

After investigating the difference between these two commands, I have found starange behavior:

Looks like git diff-index is sensitive if the file has changed but the content is not. while git diff is not sensitive in this case.

In other words if you want to know if a file is NOT changed but you don't care the timestamp of the last-change was changed, use git diff.

  • Note: I'm not sure I'm correct here.
Stav Alfi
  • 13,139
  • 23
  • 99
  • 171
  • https://git.vger.kernel.narkive.com/3Xf875jB/diff-on-touched-files-bug-or-feature talks about this peculiarity of `git diff-index` – Bergi Jan 24 '23 at 17:38