git log - display only the first x characters of commit's message

Viewed 175

I want to display only a limited number of characters (say the first 100 characters) of the commit message in git log

Currently, I used git log --oneline but this displays the first line of the message. This can be a very long line if there is no new-line-characters between lines in the message. This makes my git log ugly and not easily readable.

How can I do this?

If this is not possible to display a limited number of characters, can I display the real first line of the message, I mean if there is no break between it and the second line in the message?

2 Answers

I want to display only a limited number of characters (say the first 100 characters) of the commit message in git log

See placeholders available for --format. You're interested in %<(100) — it cuts long lines to the given number of characters; unfortunately it pads short lines at the right to the given number of characters but that's the best you can find. So you need

git log --format='%h %<(100)%s'

can I display the real first line of the message, I mean if there is no break between it and the second line in the message?

No, %s placeholder takes not the first line but the first paragraph separated by two newlines. Next time please use the best practice on how to write a good commit message:

https://chris.beams.io/posts/git-commit/#separate

You can go with more complex processing using %B and cutting the first line from it. Something like this:

git rev-parse master |
    while read sha1; do
        first_line=$(git --no-pager show -s --format='%B' | head -1)
        echo "$sha1 $first_line"
    done

Using git version 2.32.0 (Apple Git-132) on macOS Monterey Version 12.2.1, I found that in order to actually cut to the given number of characters I had to explicitly ask it to truncate output.

Like so:

git log --format='%h %<(100,trunc)%s'

From https://git-scm.com/docs/git-log#Documentation/git-log.txt-emltltNgttruncltruncmtruncem

%<(<N>[,trunc|ltrunc|mtrunc])

make the next placeholder take at least N columns, padding spaces on the right if necessary. Optionally truncate at the beginning (ltrunc), the middle (mtrunc) or the end (trunc) if the output is longer than N columns. Note that truncating only works correctly with N >= 2.

PS: I'd make this a comment or an edit for the existing answer, but I don't have enough rep for commenting and it says the edit queue is full. Anyways, wanted to add to what phd said.

Related