How to Use git log with File Filter for Specific File History
Use
git log -- <file-path> to show commit history only for a specific file or directory. This filters the log output to include commits that changed that file, helping you track its history easily.Syntax
The basic syntax to filter git log by file is:
git log -- <file-path>: Shows commits that affected the specified file or directory.- The
--separates options from file paths to avoid confusion.
bash
git log -- <file-path>Example
This example shows how to view the commit history for a file named app.js in your project:
bash
git log -- app.jsOutput
commit 9fceb02d0ae598e95dc970b74767f19372d61af8
Author: Jane Doe <jane@example.com>
Date: Mon Apr 1 12:34:56 2024 +0000
Fix bug in app.js
commit 7ac9a1f3e4b2a1f3b2c3d4e5f6a7b8c9d0e1f2a3
Author: John Smith <john@example.com>
Date: Sun Mar 31 10:20:30 2024 +0000
Add new feature to app.js
Common Pitfalls
Common mistakes when using git log with file filters include:
- Omitting the
--before the file path, which can cause Git to misinterpret the file as an option. - Using incorrect or relative file paths that do not match the repository structure.
- Expecting
git logto show changes for deleted files without specifying the correct path or commit range.
Correct usage example:
git log -- src/index.html
Incorrect usage example (missing --):
git log src/index.html
bash
git log -- src/index.html # Incorrect (missing --) git log src/index.html
Quick Reference
| Command | Description |
|---|---|
| git log -- | Show commits that changed the specified file |
| git log -p -- | Show commits with patch (diff) for the file |
| git log --follow -- | Show history including file renames |
| git log -- | Show commits affecting all files in a directory |
Key Takeaways
Always use
-- before the file path to filter git log correctly.Filtering git log by file shows only commits that changed that file or directory.
Use
--follow to track history through file renames.Provide correct relative or absolute file paths matching the repo structure.
Combine with options like
-p to see detailed changes for the file.