Question

Is it possible to staged twice the same file and compare (diff) the two staged version? Example with the file myclass.java:

  • I stage my file ==> git add myclass.java (staged file version 1)
  • I do some changes on this file
  • I stage again my file (staged file version 2)

Can I compare staged file version 1 and staged file version 2?

Thx!

Was it helpful?

Solution

The second git add overwrites the first, but you can still get the diff.

# edit edit edit
$ git add myclass.java
# edit some more

Now git diff will show you the diff between the staged file and the last edits. If you want the diff between the staged file and the last commit, you have to do git diff --staged.

OTHER TIPS

The Git index is where files are staged for commits; take a look at this StackOverflow answer for more information. When you stage files for commit, the index reflects the latest staged information. Staging a file a second time will change the Git index to reflect the file's content in the working directory.

However, with some additional work, you can see the content of the file as it was for each stage. You can use git ls-files after each stage to get a list of file blobs that you can then use later for comparison using diff or some other difference tool.

Here's a little sample session as an example.

$ git init
Initialized empty Git repository in /home/user/tmp/.git/
$ echo "foo" > foo
$ git add foo
$ git ls-files --stage
100644 257cc5642cb1a054f08cc83f2d943e56fd3ebe99 0   foo
$ echo "bar" > foo
$ git add foo
$ git ls-files --stage
100644 5716ca5987cbf97d6bb54920bea6adde242d87e6 0   foo
$ git cat-file blob 257cc56 > foo.257cc56
$ git cat-file blob 5716ca5 > foo.5716ca5
$ diff foo.257cc56 foo.5716ca5 
1c1
< foo
---
> bar

But this is a lot of work and requires careful planning and storing of blob hash values to accomplish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top