How to Find Git Commit ID by Commit Message?

To find a git commit id/hash by a full or partial commit message, you can use the git log command with the --grep=<pattern> option (where the "pattern" is a regular expression pattern).

For example, the following would perform a case-sensitive search for the word "Updated" in git commit messages and list out all that match fully or partially:

git log --grep="Updated"

Following is an example output of this command:

commit 3ba53ff050ef253058088eff5
Author: Designcise
Date:   Thu Dec 9 17:39:20 2021 +0100

    Updated tests

commit 76af06471c3a5281ff7fe38ce9
Author: Designcise
Date:   Sun Nov 14 12:34:42 2021 +0100

    Updated author list in readme

...

The commit id is the (unique SHA-1) string that appears right after the word "commit".

To perform a case-insensitive match instead, you can simply use the -i flag (or --regexp-ignore-case), for example, like so:

git log --grep="Updated" -i

This would perform a case-insensitive matching, for example, resulting in something like the following:

commit 3ba53ff050ef253058088eff5
Author: Designcise
Date:   Thu Dec 9 17:39:20 2021 +0100

    Updated tests

commit 66db03591ccb5581edf0044dfe
Author: Designcise
Date:   Thu Dec 2 17:53:47 2021 +0100

    Refactoring & updated license

...

It is possible to specify the --grep option multiple times. In that case, only those commits are displayed whose message matches at least one of the given patterns. Consider, for example, the following:

git log --grep="Updated" --grep="readme"

This would result in matching all files that have "Updated" or "readme" in the commit message, resulting in something like the following:

commit 3ba53ff050ef253058088eff5
Author: Designcise
Date:   Thu Dec 9 17:39:20 2021 +0100

    Updated tests

commit 34bc04751b3b5581ed7de32cdb
Author: Designcise
Date:   Mon Nov 15 03:00:30 2021 +0100

    Added coverage badges to readme

...

You may also limit the matches to ones that match all given --grep patterns (as opposed to at least one), by specifying the --all-match option, for example, like so:

git log --grep="Updated" --grep="readme" --all-match

This would only match commit messages that contain both "Updated" and "readme", resulting in something like the following:

commit 76af06471c3a5281ff7fe38ce9
Author: Designcise
Date:   Sun Nov 14 12:34:42 2021 +0100

    Updated author list in readme

commit 45db03581b3b5581ed7cc44dbc
Author: Designcise
Date:   Fri Nov 5 22:06:47 2021 +0100

    Updated readme

...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.