Show git diff HEAD~1 of file not touched in recent commits

diff()git

In Git, to see the differences with a previous commit I run this:

git diff HEAD~1

To see the commits related with a single file I would run this:

git log --oneline file

But if I run the following and the file I want to reference was not changed in the last commits Git shows nothing.

git diff HEAD~1 file

How can I view the diff in a way similar to HEAD but to a specific file if that file was not committed in the reference pointed at by HEAD?

Best Answer

You will have to reference the SHA explicitly if you want to see the diff of a file that was not changed between the last commit and the one before it (HEAD~1).

Run the log to see a few of the SHAs you'll want to view

git log --oneline <file>

An example output is as follows:

af46919 scraped - called local pizzeria instead
b09206c added sauce and bottle of dr pepper into list
ad90f90 knead dough and leave over night

Now if you want to see the diff of changes made for the file, you reference it via the second SHA you see. In this case we have this from the example:

git diff b09206c <file>

The above is shorthand for

git diff b09206c HEAD <file>

Or think of it like this:

git diff <start-commit-SHA> <future-commit-SHA> <file>

To run it as one command (e.g. for script) you can do:

git log --oneline <file> |awk 'NR==2{print $1}'|xargs -I {} git diff {} <file> 
Related Question