git log 常用命令

更新时间:2023-02-22 15:57:53标签:git

示例

遍历src/pages下的所有文件, 将每个文件的mtime修改为git log 中最后一次提交的时间

1#!/bin/sh
2
3git ls-tree -r --name-only HEAD src/pages | while read filename; do
4
5touch -d "$(git log -1 --format="%ai" -- $filename)" $filename
6
7done
1# 执行以上命令时注意修改git config core.quotepath,否则包含中文名称的路径将会被转移成\xx\xx从而引发报错
2git config --global core.quotepath false

应用场景

我们可以在编译期间,获取每个文件的最后提交时间,比如本项目,在执行git actions时,遍历每篇文章的最后提交时间,作为文章的最后更新时间。

示例代码

--format 参数详解

作者

  1. %an %aN 作者名称

    1git log -1 --format="%an" -- filepath
    2# output: ChenJiYuan
  2. %ae %aE 作者邮箱

    1git log -1 --format="%ae" -- filepath
    2# output: chenjiyuan.super@gmail.com
  3. %aD 提交时间(rfc2882)

    1git log -1 --format="%aD" -- filepath
    2# output: Wed Aug 24 12:33:50 2022 +0800
  4. %ar 提交时间(相对时间)

    1git log -1 --format="%ar" -- filepath
    2# output: 3 hours ago
  5. %at 提交时间(timestamp)

    1git log -1 --format="%at" -- filepath
    2# output: 1661315630
  6. %ai 提交时间(iso8601)

    1git log -1 --format="%ai" -- filepath
    2# output: 2022-08-24 12:33:50 +0800

提交者

%c 和 %a 开头的写法,一个是作者信息,一个是提交者信息,测试的输出结果一致, 不知道有什么区别

  1. %cn %cN 提交者的名字

    1git log -1 --format="%cn" -- filepath
    2# output: ChenJiYuan
  2. %ce %cE 提交者的邮箱

    1git log -1 --format="%ce" -- filepath
    2# output: chenjiyuan.super@gmail.com
  3. %cD 提交时间(rfc2882)

    1git log -1 --format="%cD" -- filepath
    2# output: Wed Aug 24 12:33:50 2022 +0800
  4. %cr 提交时间(相对时间)

    1git log -1 --format="%cr" -- filepath
    2# output: 3 hours ago
  5. %ct 提交时间(timestamp)

    1git log -1 --format="%ct" -- filepath
    2# output: 1661315630
  6. %ci 提交时间(iso8601)

    1git log -1 --format="%ci" -- filepath
    2# output: 2022-08-24 12:33:50 +0800

Hash相关

  1. %H 提交的hash

    1git log -1 --format="%H" -- filepath
    2# output: c6ededc02c13877d62f7a1b1b004ca8db7d1dd1d
  2. %h 提交的hash(缩写,前七位)

    1git log -1 --format="%h" -- filepath
    2# output: c6ededc
  3. %T 树hash(tree hash)

    1git log -1 --format="%T" -- filepath
    2# output: 74c55360530c7f38e6f459b5d4d32a5ce7a973ac
  4. %t 树hash(简写)

    1git log -1 --format="%t" -- filepath
    2# output: 74c5536
  5. %P parent hash

    1git log -1 --format="%P" -- filepath
    2# output: e224982135575c4cf4c7bbdc9cf70c228444f10c
  6. %p parent hash(简写)

    1git log -1 --format="%p" -- filepath
    2# output: e224982

Commit 相关

  1. %s 提交信息的标题

    1git log -1 --format="%s" -- filepath
    2# output: Fix some bugs
  2. %f 提交信息的标题(格式化后)

    1git log -1 --format="%f" -- filepath
    2# output: Fix-some-bugs
  3. %b 提交信息的body

    1git log -1 --format="%b" -- filepath
    2# output: 1. improve xxxx
    3# 2. fix xxx
  4. %d ref name

    1git log -1 --format="%d" -- filepath
    2# output: (HEAD -> master, origin/master)
  5. %e encoding(不知道是啥)