gitgit-rev-list

`git rev-list --grep` only first line of commit message


Consider a git history with the following two commits (among others).

Fix-123 - Fix Foo

Foo was broken. This change fixes it.
Fix-456 - Fix Bar

Fix-123 broke Bar. This change fixes it.

Is it possible to use the --grep flag of git rev-list to find only commits whose messages begin with Fix-123? Using the anchor ^ alone isn't sufficient, since by default git interprets this as the beginning of a line, not the beginning of the entire message. So for example git rev-list --grep "^Fix-123" will match both of the above commits, since the second line of the commit for Fix-456 also begins with Fix-123.

I realize I could perform an initial search with git log --grep and then pipe to some further processing step to filter down, but since I'm ultimately just interested in the commit hash, doing it that way would be much less elegant.


Solution

  • git log --oneline | grep " Fix-123"
    

    git log --oneline prints one line for every commit in the format "hash 1st line of the message". grep filters by the message.

    To grep for message that guaranteed to start with the search text:

    git log --pretty=oneline --no-abbrev-commit | grep "^[a-z0-9]\{40\} Fix-123"
    

    git log --pretty=oneline --no-abbrev-commit prints hashes in full length (40 characters); grep "^[a-z0-9]\{40\}" searches (actually, skips) these hashes.