What is git log --grep
?
The git log
command displays the commit history of the current branch. By adding the --grep
option, you can filter this log to show only those commits whose commit message contains a certain string or matches a regex pattern.
This guide explains how to use git log --grep
effectively, including searching commit messages, the entire project history, and across all branches.
Using git log --grep
to filter commit messages
Basic string search: To find commits with a specific string in their commit message, you can use:
Terminalgit log --grep="Fix bug"This command displays all commits where the commit message contains "Fix bug".
Regular expression search: If you're looking for commits with messages that match a more complex pattern, you can use regular expressions (regex):
Terminalgit log --grep="JIRA-[0-9]+"This regex pattern matches commit messages that refer to a JIRA ticket, such as "JIRA-1234".
For combining patterns that should match any of the specified conditions (OR logic), you can use regular expressions within a single
--grep
option:Terminalgit log --grep="\(UI\|bug\)"This uses the regular expression
\(UI\|bug\)
to find commits whose messages contain either "UI" or "bug".
Advanced search techniques
Case-insensitive search: Add the
-i
option to perform a case-insensitive search:Terminalgit log --grep="fix bug" -iCombining multiple --grep conditions If you need to find commits that must meet multiple criteria (AND logic), you can specify multiple
--grep
options. This will work becausegit log
implicitly uses AND logic when multiple--grep
flags are used:Terminalgit log --grep="UI" --grep="bug"This command will return commits that contain both "UI" and "bug" in their messages, as
git log
treats multiple--grep
conditions as needing to all be true.Searching across all branches: To extend the search across all branches, include the
--all
flag:Terminalgit log --all --grep="UI update"Searching for strings in files: If you want to search the history for a specific string within the files (not just the commit messages), use
git grep
in combination withgit log
:Terminalgit grep "functionName" $(git rev-list --all)This command searches for "functionName" in all files across the entire history of the repository.
For further reading on searching the log with grep
see the official Git documentation.