0
0
GitHow-ToBeginner · 3 min read

How to Search in Git History: Commands and Examples

To search in Git history, use 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.

bash
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.

bash
git log --grep="update" --oneline

git log -S"config" --oneline
Output
a1b2c3d Update README with new instructions f4e5d6a Update config handling b7c8d9e Added config validation c0d1e2f Removed old config code
⚠️

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.

bash
Wrong:
git log --grep=fix bug

Right:
git log --grep="fix bug"
📊

Quick Reference

CommandDescription
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

Use git log --grep to search commit messages by keyword.
Use git log -S to find commits that changed specific code.
Always quote your search patterns to avoid shell issues.
Use git grep with commit references to search code in history.
Remember git grep alone searches only current files, not history.