To view the change history of a file in Git, use the commands below to track modifications, authors, and timestamps. Here’s a step-by-step guide with examples:
1. Basic File History
Show all commits affecting a specific file, including diffs (changes):
git log -p <file-path>
Example:
git log -p src/app.js
-p
shows the diff (actual code changes) in each commit.- Use
-- <file>
to avoid ambiguity if the filename matches a branch name.
2. Simplified History
List commits in a compact format (author, date, message):
git log --oneline -- <file-path>
Example:
git log --oneline -- README.md
Output:
d3f4a5f Update README
a1b2c3d Add project setup guide
3. Track File Renames
Include commits from before the file was renamed/moved:
git log --follow -p <file-path>
Example:
git log --follow -p docs/new-guide.md # Tracks history even if renamed from `old-guide.md`
4. View Changes by Author
Filter commits by a specific author:
git log --author="John" -- <file-path>
5. Annotate Line-by-Line Changes
See which commit last modified each line (blame):
git blame <file-path>
Example:
git blame utils/helpers.py
Output:
a1b2c3d (Alice 2023-10-01 14:30:00 -0400 1) def calculate_sum(a, b):
d3f4a5f (Bob 2023-10-02 09:15:00 -0400 2) return a + b
6. Compare Changes Between Branches
Show commits modifying the file in feature-branch
but not in main
:
git log main..feature-branch -- <file-path>
7. View Changes Over Time (GUI)
Use Git’s built-in GUI to visualize history:
gitk <file-path>
- GitKraken, VS Code GitLens, or GitHub/GitLab’s web interface also provide visual histories.
Common Scenarios
View changes before a specific date:
git log --until="2023-09-30" -- <file-path>
Find when a bug was introduced:
git log -S "error_message" -- <file-path> # Search for string in diffs
See only merge commits affecting the file:
git log --merges -- <file-path>
Key Notes
- Replace
<file-path>
with the file’s relative path (e.g.,src/script.js
). - Use
git show <commit-hash>:<file-path>
to view the file’s content at a specific commit. - If the file was deleted, use
git log -- <file-path>
to see its history before deletion.
Example Workflow
- Check full history with diffs:
git log -p package.json
- Find recent changes (last 3 commits):
git log -3 -p package.json
- Blame a file to debug a specific line:
git blame -L 10,20 config.yml # Lines 10-20
Troubleshooting
- No history found? Ensure the file exists in the repository (check with
git ls-files
). - File not tracked? Use
git add
first to include it in version control.