Search All of Your Git History for Code and Commits with 2 Commands
Search your git repos for any string / regex, even across branches. This is handy to recall something from days, weeks or years ago.
Quick Jump: Demo Video
You can use the
git grep (or
rg, etc.) command to search through code in the current git working tree / directory but what if you want to search for something in an older commit?
If you’re searching for code within commits you can use the git “pickaxe” flag, here’s a few examples. All of these commands will identify specific commits that contain your search term at least once and you can choose to see the matches too:
# Show commits that contains the code, then you can: git show <commit_sha> git log -S "whatever you want to search for" # An even easier way to show matches right there on the spot git log -S "your search term" -p # Same as above, except applied to all branches instead of the checked out branch git log -S "something" -p --all # Limit your search to only specific files in a specific directory git log -S "something specific" -p -- **/models/user*.py # Search for a regex instead of a string (note the -G instead of -S) git log -G '^alias \w+=".*"$' -p
Now let’s say you don’t remember the code but instead you remember reading or committing a specific message. Git lets you search commit messages too:
# Show the commit message that contains your search term, you can supply either # a string or regular expression with the same flag git log --grep "your search term" # Same as above, except applied to all branches instead of the checked out branch git log --grep "something else" --all
- 0:52 – Searching for a string in code that exists in any commit
- 2:09 – Quality of life improvement for searching with the patch flag
- 2:57 – Applying this to all branches with the all flag
- 3:50 – Filter the matches by a specific directory or file type
- 5:58 – Doing a regex search in code in any commit
- 7:37 – Searching through git commit messages with strings or a regex
I use these commands a few times a month, how about you? Let me know below.