git diff
is a command used to compare changes between commits, branches, and your working directory. It’s handy for identifying differences in your code before you commit or push changes.
Initial Example
Comparing the working directory with the local repository using:
$ git diff HEAD <filename>
DIFF Options
Option | Description |
---|---|
git diff [<options>] [<commit>] [--] [<path>…​] | Show changes between the working directory and the index or a tree, or between two trees. |
git diff HEAD <filename> | Compares the changes in the working directory with the latest commit in the local repository. |
git diff <source branch> <target branch> | Compares the differences between two branches, showing changes from the source branch to the target branch. |
--staged | Shows changes between the staged files and the last commit. |
--cached | Synonym for --staged , displays changes between the index and the last commit. |
--name-only | Displays only the names of changed files. |
--name-status | Shows the names and status (e.g., added, modified, deleted) of changed files. |
--color | Forces color output. |
--stat | Shows a summary of changes with statistics. |
<commit1> <commit2> | Compares the differences between two commits. |
--shortstat | Displays only the short statistics of changes. |
--diff-filter=[ACMRTD] | Filters the diff to include only files with specific statuses (e.g., Added, Copied, Modified, Renamed, Deleted). |
--raw | Prints the raw output format. |
-v , --verbose | Prints the contents of the tag object before validating it. |
Example
1. Comparing Working Directory with Local Repository
To compare the changes in your working directory with the latest commit in the local repository, use the following command:
$ git diff HEAD <filename>
This will show the differences between the specified file in your working directory and the latest committed version.
2. Comparing Two Branches
To compare the differences between two branches, use the following command:
$ git diff <source branch> <target branch>
This command will display the changes between the source branch and the target branch, helping you to understand what has been modified before merging or pushing changes.