Git Log 格式化输出

默认的git log展示出的内容过于详细,如果想要浏览多个最近提交,例如一次查看最近100比提交,
需要不停的翻译稍显麻烦,同时git log提供了自定义输出格式的功能,可以通过–format来定制
git log的展示格式。

安装新版本Git

首先更新git到较新版本,Ubuntu 20.04默认安装的git版本为较早期的2.25.1.

添加git 官方PPA仓库:

sudo add-apt-repository ppa:git-core/ppa

更新并安装新的git:

sudo apt update
sudo apt install git

验证:

git –version

输出:

git version 2.49.0

配置bashrc或者zshrc脚本

参考Git 文档:https://git-scm.com/docs/pretty-formats

添加脚本:这里将log分成四列: 日期 | 短哈希 | 作者 | 部分提交信息

1
2
3
4
5
6
7
8
9
10
11
lg() {
if [ "$1" != '' ]; then
if [[ $1 =~ ^[0-9]+$ ]]; then
git log --pretty=format:"%<(16,trunc) %ch | %h |%<(10,trunc) %al |%<(85,trunc) %s" -n $1 . | cat
else
git log --pretty=format:"%<(16,trunc) %ch | %h |%<(10,trunc) %al |%<(85,trunc) %s" $@ | cat
fi
else
git log --pretty=format:"%<(16,trunc) %ch | %h |%<(10,trunc) %al |%<(85,trunc) %s" -n 20 . | cat
fi
}

刷新脚本:

source ~/.zshrc

使用方法

  1. 默认方法: 默认展示最近的20笔提交

    lg

  2. 指定特定数量的提交, 例如100条

    lg 100

  3. 搭配其他git log参数, 可搭配任意git log参数, 例如查看某个日期范围内的提交:

    lg –since=”2025-05-01” –until=”2025-05-31”

除了使用git的参数外, 同样可以搭配管道操作使用