Git Diff
In the world of version control, Git's git diff
command is a fundamental tool
that allows developers to compare changes between different states of a repository. We'll explore the various ways you can leverage the git diff
command
to examine and understand the differences in your project's codebase.
1. Basic Usage:
The most straightforward use of git diff
involves comparing the working
directory with the last commit. Execute the following command to see the unstaged changes:
bashgit diff
This command displays the line-by-line differences between your current working directory and the last commit.
2. Staged Changes:
To view the changes that are staged but not yet committed, use the --staged
or
-cached
option:
bashgit diff --staged
This is useful for reviewing the modifications you are about to commit.
3. Comparing Specific Commits:
Compare the changes between two specific commits by providing their commit hashes:
bashgit diff commit-hash-1 commit-hash-2
This command illustrates the differences between the specified commits.
4. Viewing Changes in a File:
To focus on changes within a specific file, provide the filename after the
git diff
command:
bashgit diff file-name
This narrows down the output to changes made in that particular file.
5. Side-by-Side Diff:
Enhance readability by using the --word-diff
and --word-diff-regex
options for a side-by-side, word-level diff:
bashgit diff --word-diff --word-diff-regex=.
This provides a more detailed view of changes at the word level.
6. Ignore Whitespace Changes:
Filter out whitespace changes to focus on meaningful code modifications:
bashgit diff -w
This can be particularly helpful when reviewing changes that only involve indentation or spacing.
7. Viewing Unified Diff:
Display the changes in a unified diff format, which is commonly used for patches:
bashgit diff --unified=3
The --unified
option controls the number of context lines in the output.
8. Comparing Branches:
Compare changes between two branches:
bashgit diff branch-name-1..branch-name-2
This shows the differences between the tip of one branch and the tip of another.
9. Visualizing Changes Graphically:
Leverage external tools like git difftool
to visualize changes graphically.
Popular tools include meld, kdiff3, and vscode:
bashgit difftool -t meld
This opens the meld tool for a visual representation of the changes.
10. Patch Mode:
Enter interactive patch mode to selectively stage changes. This allows you to review and choose which modifications to include in the next commit:
bashgit add -p
Navigate through each change, deciding whether to stage, skip, or split modifications.