How to Search for Specific String in the Git Commit History
This article outlines the different methods we use to search through Git history for a specific string.
Skimming through the commit messages in your history does not always make the cut. Sometimes you want to know which commits were affected by a specific variable or string.
We can add some arguments to the git log
command to search for a string, and Git will give us the commits that are adding or deleting the string from our repo’s history. This feature makes it simple to understand the commit context for a particular piece of code.
Search for Specific String in the Git Commit History
In our first scenario, we want to search for all the commits where the commit message has the word Update
. How do we go about this?
We will run the git log
command as shown below.
$ git log --grep=Update
Output:
As seen from the output above, Git gave us only the commits with the word Update
.
Say we wanted to search for commits where the "php"
string has been added or removed in the files. How do we go about it?
We can run the git log
command with the -S
flag as shown below:
$ git log -S "php"
Output:
To get a diff of this, we will run the command below:
$ git log -S "php" -p | grep "php" -C5
If you have a lot of commits with the string, it is best to use a difftool. You may get confused because Git will give you a chunky output.
We can also use the git log
command with the -G
argument to search for differences where the added or removed lines match "php"
as shown below;
$ git log -G "php"
Note:
-G
accepts a regex while-S
accepts strings.- The
-S
argument will find the commits where the word changes while-G
searches for the word in the diff.
We can add arguments to the git log
command to manipulate the output. We discussed how you could search for strings in our commit history using common scenarios.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn