2

How can I extract the commit message (and only/exactly the commit message) of a commit?

git show https://git-scm.com/docs/git-show doesn't seem to have an option for that

I could do git cat-file -p <commit_hash> and then search for the first \n\n and take everything after that until EOF, or I could do git log --format=%B -n 1 <commit_hash> but what is likely going to be forward compatible with future git versions? (of course, there's never a guarantee for that, but there's probably a 'best way' of doing this)

jub0bs
  • 60,866
  • 25
  • 183
  • 186
matthias_buehlmann
  • 4,641
  • 6
  • 34
  • 76
  • Have you looked at `git rev-list`? It's more or less the Plumbing equivalent of `git log`. – jub0bs Feb 08 '21 at 14:42
  • 1
    the linked answer also prints out the commit hash of the commit. is it 'safe' to just remove everything up until the first \n ? – matthias_buehlmann Feb 08 '21 at 14:48
  • Ah yes. Sorry, I closed this as a dupe too quickly. Reopening. – jub0bs Feb 08 '21 at 14:49
  • See [this comment](https://stackoverflow.com/questions/39420225/extract-commit-message-using-git-rev-list#comment66166309_39420243) from torek. – jub0bs Feb 08 '21 at 15:04

1 Answers1

5

I would avoid trying to parse a file directly; using a git command is likely to provide a backward compatible API even if the underlying data format changes.

I would use avoid git log but instead use git show, which will let you examine a particular commit (instead of a range, which git log intends to do). It does, in fact, have an option for that, allowing you to specify custom formatting options.

To show only the commit message subject and body, use the %B format and turn off patch display.

git show --pretty=format:"%B" --no-patch
Edward Thomson
  • 74,857
  • 14
  • 158
  • 187