Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

You've probably run into this problem a few times: you're working on a feature and discover a code section that doesn't make sense to you. There's no context, no comments, no help โ€” it's just you and these mysterious lines staring right back at you.

// when was this added? ๐Ÿ‘‡
if (someVar === 1.32) {
  // ...
}

You try to use git blame to learn more about the mysterious code, but recently applied code style changes and refactorings hide the commit when these lines have entered the code base. Looking at the file history isn't of great help either because the code base is old, and this particular file is very busy.

Today I learned that the Git log command includes a -S flag to help with this exact problem.

# search for a string in file additions or deletions
git log -S 'if (someVar === 1.32)'
commit 08f579675fc62c63cd182b580dc80fac53b02526
Author: stefan judis <stefanjudis@gmail.com>
Date:   Sun Nov 28 20:06:04 2021 +0100

  developing a mysterious feature

-S scans all commit additions and deletions, looking for your defined substring. So, if you're looking for a weird-looking variable or unique condition, you'll find the commit that added it quickly. git log -S is pretty neat!

Big thanks go to Alex Harri, who shared the flag and some more advanced Git -S combinations:

# start with the oldest commits first
git log -S "YOUR STRING" --reverse

# only show commit hash and message
git log -S "YOUR STRING" --oneline

Happy commit searching!

If you enjoyed this article...

Join 5.4k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles