0
0
GitHow-ToBeginner · 3 min read

How to Use Git Diff: Compare Changes Easily

Use git diff to see the differences between files or commits in your Git repository. It shows what has changed but not yet committed, helping you review code before saving changes permanently.
📐

Syntax

The basic syntax of git diff lets you compare changes in different ways:

  • git diff: Shows unstaged changes in your working directory.
  • git diff --staged: Shows changes staged for the next commit.
  • git diff <commit1> <commit2>: Compares two commits.
  • git diff <branch1> <branch2>: Compares two branches.
bash
git diff [options] [<commit>] [--] [<path>...]
git diff --staged

# Examples:
git diff

# Compare two commits:
git diff commit1 commit2

# Compare two branches:
git diff branch1 branch2
💻

Example

This example shows how to use git diff to see changes made to a file before committing.

bash
echo 'Hello World' > file.txt
# Add file and commit
git add file.txt
git commit -m "Add file.txt with Hello World"

# Change file content
echo 'Hello Git' > file.txt

# Show unstaged changes
git diff file.txt
Output
diff --git a/file.txt b/file.txt index e69de29..d95f3ad 100644 --- a/file.txt +++ b/file.txt @@ -1 +1 @@ -Hello World +Hello Git
⚠️

Common Pitfalls

Common mistakes when using git diff include:

  • Expecting git diff to show staged changes (use git diff --staged instead).
  • Not specifying files or commits correctly, leading to confusing output.
  • Forgetting that git diff only shows differences and does not change files.
bash
git diff  # Shows unstaged changes

git diff --staged  # Shows staged changes

# Wrong: expecting staged changes with just git diff
# Right: use git diff --staged to see staged changes
📊

Quick Reference

CommandDescription
git diffShow unstaged changes in working directory
git diff --stagedShow changes staged for next commit
git diff Compare two commits
git diff Compare two branches
git diff -- Show changes for a specific file

Key Takeaways

Use git diff to see changes not yet staged for commit.
Use git diff --staged to review changes ready to be committed.
You can compare commits or branches by specifying them in git diff.
Always check your changes with git diff before committing to avoid mistakes.
Remember git diff only shows differences; it does not modify files.