How to Search in Git History: Commands and Examples
git log with options like --grep to find commits by message or git log -S to find commits that added or removed specific code. For searching code content in the repository history, use git grep.Syntax
git log --grep=<pattern>: Searches commit messages for the given pattern.
git log -S<string>: Finds commits that added or removed the specified string in code.
git grep <pattern>: Searches the working directory or specific commits for the pattern in files.
git log --grep="fix bug" git log -S"initialize" git grep "TODO"
Example
This example shows how to find commits with the word "update" in their message and how to find commits that added or removed the word "config" in the code.
git log --grep="update" --oneline git log -S"config" --oneline
Common Pitfalls
Using git log --grep only searches commit messages, not code changes. To find code changes, use git log -S instead.
Not using quotes around search patterns can cause shell errors or unexpected results.
For searching code content in history, git grep alone searches current files, not history. Use it with commit references to search past versions.
Wrong: git log --grep=fix bug Right: git log --grep="fix bug"
Quick Reference
| Command | Description |
|---|---|
| git log --grep="pattern" | Search commit messages for 'pattern' |
| git log -S"string" | Find commits adding/removing 'string' in code |
| git grep "pattern" | Search current files for 'pattern' |
| git grep "pattern" $(git rev-list --all) | Search all commits for 'pattern' in files |
Key Takeaways
git log --grep to search commit messages by keyword.git log -S to find commits that changed specific code.git grep with commit references to search code in history.git grep alone searches only current files, not history.