You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让git log仅在提交存在正文时为主题行追加省略号?

Git Log 条件追加省略号解决方案

问题背景

假设Git历史记录如下:

$ git log --oneline
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob
ac27e4d Revert "do something special"
338ff0f do something special
...

其中966a640和ac27e4d包含额外提交正文,f9b86d3和338ff0f只有主题行(正文为空)。需要编写Git Log的格式说明符,实现仅当提交存在正文时,在主题行末尾追加省略号,期望输出:

$ git log --abbrev-commit --pretty='自定义格式'
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob ...
ac27e4d Revert "do something special" ...
338ff0f do something special
...

之前尝试过%h%d %s%<(1,trunc)% b的写法,虽然能判断正文存在并添加符号,但会保留正文中的换行符,导致输出混乱:

$ git log --abbrev-commit --pretty='%h%d %s%<(1,trunc)% b'
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob ..




ac27e4d Revert "do something special" ..


338ff0f do something special

解决方案

使用Git的条件格式语法,仅在提交正文非空时追加省略号,命令如下:

git log --abbrev-commit --pretty='%h%d %s%(if:not blank=%b)%(then) ...%(end)'

语法说明

  • %h%d %s:输出缩写提交哈希、分支标记和主题行,是基础格式内容
  • %(if:not blank=%b):判断提交正文(%b)是否不为空
  • %(then) ...%(end):如果条件成立,就在主题行末尾追加 ...(前面的空格用于和主题行分隔开)

这个写法仅用%b做存在性判断,不会输出任何正文内容,因此不会引入正文里的换行符,完全符合期望输出。


内容的提问来源于stack exchange,提问作者vergenzt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:15:23