user123444555621
user123444555621

Reputation: 153234

Git: Show content of file as it will look like after committing

After reading Git pre-commit hook : changed/added files, the following question arose:

Given I have a file with both staged and unstaged changes, how can I display a preview of the file's contents after staging?

Example:

echo "foo" >> file
git add file
echo "bar" >> file

Wanted output:

[previous contents of file]
foo

Upvotes: 52

Views: 19357

Answers (4)

grawity_u1686
grawity_u1686

Reputation: 16637

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

git show :file

See gitrevisions (which uses the term 'stage 0' for the "normal" index contents):

:[<n>:]<path>, e.g. :0:README, :README

A colon, optionally followed by a stage number (0 to 3) and a colon, followed by a path, names a blob object in the index at the given path. A missing stage number (and the colon that follows it) names a stage 0 entry. During a merge, stage 1 is the common ancestor, stage 2 is the target branch’s version (typically the current branch), and stage 3 is the version from the branch which is being merged.

Upvotes: 130

Mark Longair
Mark Longair

Reputation: 468081

Update: the answer from grawity has a much neater solution

This recipe is from jleedev's answer to another question:

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

You might want to create a git alias for that if you're going to use it often.

Upvotes: 6

Tollef Fog Heen
Tollef Fog Heen

Reputation: 221

You can do git diff --cached, but this isn't exactly what you want.

git grep -h --cached ^ -- file

works for me.

Upvotes: 1

Daniel B&#246;hmer
Daniel B&#246;hmer

Reputation: 15411

Just have a look at the top answer for this question: How do I show the changes which have been staged?

The --cached option is what you want.

Upvotes: -2

Related Questions