Overview
There are times when you need to know what was changed between two points. Examples are: your last commit, and your working tree; two commits; two tags; two branches; a tag and a commit.. and on. Mostly, you’ll need to know how your working tree differs, or how your staging area differs from the last commit made. For this, as you have undoubtedly already guessed, is what the git diff
command is for. Let’s look at common uses of this command.
Working tree and commit
The first situation we’ll look at is looking at the changes between your working tree, and your head. If you have made changes to your working tree, and would like to see what the changes are, git diff
with no options will show you all of them. In other words, the changes that could be added to the index to be included in the commit.
git diff
, as you may have surmised from the description, will not show you staged changes without. You need to add the --cached
or --staged
option to the command resulting in the form git diff --cached
or git diff --staged
. They are synonymous
Between Two Commits
Sometimes, you would like to see what has changed between two commits. Let’s say you have two commits, 23ad451 and 78dfe33, and would like to see the changes between them. All you have to do is provide git diff
with these commits in this form git diff 23ad451 78dfe33
, and you will see all the changes between those two commits. You may swap out any commit in this form with branches, or tags to reference those instead.
Limiting to a Named Path
Commonly, you would like to see the changes of only one file, or of only one directory. This can be accomplished by appending -- [<paths>...]
to the end of the any of the forms already mentioned. As an example, if you wanted to see the changes between commit 23ad451, and 78dfe33 for the file index.htm, the following code would do it: git diff 23ad451 78dfe33 -- index.htm
Learn More
These are just the operations I feel are very common with the diff command. If you need to do something that falls outside of this, you can read more about this command here.