Git Diff Basics
Understanding Git Diff Command
Git diff is a powerful version control command that allows developers to track and compare code changes across different stages of a project. As a critical tool in software development, the git diff command helps identify modifications between commits, branches, and working directories.
Core Concepts of Git Diff
The git diff command serves multiple purposes in tracking code changes:
Diff Type |
Description |
Use Case |
Working Directory |
Shows unstaged changes |
Local file modifications |
Staged Changes |
Compares staged files with last commit |
Pre-commit review |
Between Commits |
Compares different commit versions |
Historical code evolution |
Basic Git Diff Usage
## Compare working directory with last commit
git diff
## Compare staged changes
git diff --staged
## Compare specific files
git diff path/to/file.txt
Diff Workflow Visualization
graph LR
A[Working Directory] -->|git diff| B[Uncommitted Changes]
B -->|git add| C[Staged Area]
C -->|git diff --staged| D[Last Commit]
Practical Code Change Demonstration
Let's explore a practical example of tracking code modifications in a Python project:
## Initialize git repository
git init project
cd project
## Create sample Python file
echo "def hello_world():" > main.py
echo " print('Hello')" >> main.py
## First commit
git add main.py
git commit -m "Initial commit"
## Modify file
echo " print('Hello, World!')" >> main.py
## View changes
git diff
This example demonstrates how git diff reveals incremental changes in source code, providing developers a comprehensive view of modifications across different project stages.