63

I created a repo, created a file inside it, put some content in the file, and committed the file. Now, I'd like to see a diff of that commit, which should ideally show the file that was added and the lines that were added to it.

However, git diff HEAD^ HEAD returns fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree., probably because this was the first commit to the repo.

How can this be resolved? Is there still a way to view a diff of the files that were added in the first commit?

3
  • 4
    git show can work. But the first diff is always from null to the whole content. Commented Nov 30, 2016 at 8:50
  • @ElpieKay That works, but that also includes the commit summary. Possible to have it print only the diff without the commit summary If I do git show <file>? Commented Nov 30, 2016 at 8:54
  • git show <commit> --pretty=%% | sed 1,2d. %% could be any placeholder which outputs only one line, e.g. %h, %t. Commented Dec 1, 2016 at 12:40

4 Answers 4

158

You can do:

git diff 4b825dc642cb6eb9a060e54bf8d69288fbee4904 HEAD

4b825dc642cb6eb9a060e54bf8d69288fbee4904 is the id of the "empty tree" in Git and it's always available in every repository.

Sign up to request clarification or add additional context in comments.

11 Comments

@CharlesBaley, Cool, Where do you get this sha-1 code?
The id of the empty tree won't change while git continues to use sha1. You can use $(printf '' | git hash-object -t tree --stdin) for better readability.
@gzh: I remember common sha1s.
This is hilarious to me. Why not add a named flag for this? Something like git diff --empty-tree head. Similar to how we have --root for interactive rebase.
@DanielWaltrip maybe this is new, but git diff-tree now has a --root option that does exactly what you were asking about.
|
11

Now that Git has experimental support for SHA256 and a transition plan for migrating the hash function from SHA1 to SHA256, you can no longer rely on a hash constant for the empty tree. Instead, it's best to dynamically retrieve it based on whatever hash function your repository is using:

git diff $(git hash-object -t tree /dev/null)

Comments

1

you can try:

git show <first-commit-sha>

or if you only have 1 commit you can simply use:

git show HEAD

1 Comment

It doesn't show the diff.
0

Maybe try with:

git log -p -n 1

1 Comment

This doesn't show the first commit. It shows the most recent one. It's not an answer to the given question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.