Let's say I have a clone of a remote repository:
git clone https://git.savannah.gnu.org/git/hello.git
And that I've recently fetched changes like this:
cd hello
git fetch origin master
Inside my work tree, I modify a file:
sed -i s/GNU/MOO/g README
At this point, both git diff README
and git diff FETCH_HEAD -- README
will show the same content, because the file in my local repository and the remote repository are identical. But let's say I stage the change to be committed:
git add README
Now, running git diff README
will return nothing, because git diff
compares the work tree to the index (and running git add README
added the modified version of README
to the index)...but git diff FETCH_HEAD -- README
still returns a difference, because while my local files matches what's in my index, it differs from what is stored in (our local cache of) the remote repository.
(It's important to note here that we're never actually comparing anything against the remote repository: the only commands that interact directly with a remote are things like fetch
, pull
, and push
. Everything else is interacting with local data that reflects what the remote looked like last time we ran git fetch
; any changes that occurred in the remote repository since that point will be unknown to us until we next update our local cache.)
Address your questions in the comments:
What is meant by the "index" and how does that differ from what is in the remote?
The git index is described in the git community book. It is effectively the staging area that holds thing you git add
before they are committed to the local repository.
See also this question,
In this scenario you give, if I always follow up my "git add" with a "git commit and git push", then wouldn't redoing the "git fetch" method I mentioned result in the same output, i.e. no differences?
Sure. If you follow git push
with git fetch
, then your local
repository will reflect the state of the remote repository (it's
always possible that someone else will make changes between your git push
and git fetch
, so it's possible you would see differences,
but it's unlikely).
Is it then okay that, assuming I am always committing after using git add, to treat git diff as equivalent? I.e. as a way to check my changes against the remote?
Not generally, no. git diff
shows you how a file differs from your
local repository, If you want to compare your changes to a remote
branch, then ensure your local cache is up-to-date (git fetch origin master
, or maybe git remote update
), and then diff against the
appropriate remote branch (git diff FETCH_HEAD
or git diff origin/master
, etc).