How can I get content of a file from git index?

9.3k views Asked by At

I have a file which has been already added to my local repository. I've modified it in the working tree, so git status shows me the file as modified. I would like to know what is the file content kept in the index before I stage the file.

I can think of two ways of doing that:

  1. revert a patch generated by git diff, and apply it on the file in the working tree
  2. use git checkout-index, point to a temporary file and read the content from there

Is there an easier way?

3

There are 3 answers

3
user1686 On BEST ANSWER

Use the : prefix to access objects in the current index (staged but not yet commited).

git show :file

See the gitrevisions manual for more information.

0
Josh Lee On

To cat a file out of the index, I’m not sure of a preexisting scriptable way, but you can use ls-files to query the index:

$ git ls-files -s README
100644 67cfeb2016b24df1cb406c18145efd399f6a1792 0   README
$ git cat-file blob 67cfeb2016b24df1cb406c18145efd399f6a1792
# etc.

You can put the commands together like this:

git cat-file blob $(git ls-files -s README | awk '{print $2}')

(Although surely I am reinventing the wheel here.)

However, if you just want to open the original and your changes in an editor, use the difftool command. It copies the indexed version to a temporary file for you and opens vimdiff (or anything you want), and it is very flexible.

1
Abizern On

There are Three ways of getting diffs with git

git diff graph

so to see what the difference is between the file in the working directory and the index you just need to:

git diff name_of_file

I've written about this in more detail elsewhere