git log grep — Search a git repository for a particular commit message — Big Fat Software, Inc.
In Unix, if you want to find a piece of text, you generally grep
it. You check the logs or ps -ef
or lsof -i
or you do an ls -l
and then use grep
on it. In a similar fashion - How do you find a piece of text in your entire commit history?
To search commit-message one-liners
git log --pretty=oneline --abbrev-commit --grep="TICKET-1234"
Try these too:
git log --grep="TICKET-1234"
git log --name-status --grep=""
git log --pretty=oneline --abbrev-commit --grep=""
git log --pretty=oneline --abbrev-commit --name-status --grep=""
git log --pretty=format:%s --grep=""
Simple Unix grep:
git log | grep -b3 "TICKET-1234"
git log --pretty=oneline | awk '{print $1}'
Creating an alias
If you haven’t read about creating aliases, then read the following articles:
- How to define aliases in
git
- https://coderwall.com/p/euwpig/a-better-git-log
- http://durdn.com/blog/2012/11/22/must-have-git-aliases-advanced-examples/
Add this in your ~/.gitconfig
:
[alias] find = log --pretty=\"format:%Cgreen%H %Cblue%s\" --name-status --grep
Usage:
git find "string"
Add this in your ~/.gitconfig
:
[alias] lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
Usage:
git lg --grep=""
The snippet above does the same thing as the following:
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
To search and grep across all branches and and all commit messages for the given piece of text :
git log --all --grep='TICKET-1234'
git log --pretty=\"format:%Cgreen%H %Cblue%s\" --name-status --grep
To search the actual content of commits through a repository’s history:
Caution: It can take a while to execute
git grep 'TICKET-1234' $(git rev-list --all)
To show all instances of the given text, the containing file name, and the commit SHA-1.
git grep 'TICKET-1234' $(git rev-list --all)
If your commit is not connected to history at all, you can search the reflog
itself with the (short for --walk-reflogs
:
git log -g --grep='TICKET-1234'
If you seem to have lost your history, check the reflog
as your safety net. Look for Build 0051 in one of the commits listed by
git reflog
You may have simply set your HEAD
to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.
To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)
git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
git checkout HEAD@{10}
# make a new branch with the build_0051 as the tip
git checkout -b build_0051
Originally published at http://bigfatsoftwareinc.wordpress.com on December 24, 2020.