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

如何实现Git显示指定路径差异且不跳过未改动路径的提交?

解决Git提交记录显示指定路径差异的需求

要实现显示develop..mybranch区间内的所有提交,同时仅对修改过指定路径(比如mydir)的提交展示对应差异,可以用以下bash脚本实现:

git log --format="%H %s" develop..mybranch | while read hash msg; do
    # 输出提交基本信息
    echo "commit $hash"
    echo "    $msg"
    
    # 判断当前提交是否有父提交(处理初始提交场景)
    if git rev-parse --verify $hash^ >/dev/null 2>&1; then
        # 检查提交是否修改了目标路径
        if git diff --name-only $hash^ $hash | grep -q "^mydir"; then
            # 展示该路径的差异
            git diff $hash^ $hash -- mydir
        fi
    else
        # 初始提交,检查是否包含目标路径
        if git ls-tree --name-only $hash | grep -q "^mydir"; then
            git show $hash -- mydir
        fi
    fi
    echo ""
done

脚本说明

  • git log --format="%H %s" develop..mybranch:获取指定提交区间内的所有提交哈希和提交信息,不会过滤任何提交。
  • 循环遍历每个提交,先输出提交的哈希和说明信息。
  • git rev-parse --verify $hash^:判断当前提交是否存在父提交,避免初始提交(无父提交)执行git diff报错。
  • git diff --name-only $hash^ $hash | grep -q "^mydir":静默检查提交是否修改了mydir路径,匹配到则执行差异展示。
  • 初始提交场景下,用git ls-tree检查该提交是否包含目标路径,存在则用git show展示内容。

如果不需要处理初始提交的特殊场景,可以简化成更简洁的版本:

git log --format="%H %s" develop..mybranch | while read hash msg; do
    echo "commit $hash"
    echo "    $msg"
    git diff --name-only $hash^ $hash | grep -q "^mydir" && git diff $hash^ $hash -- mydir
    echo ""
done

内容的提问来源于stack exchange,提问作者H.v.M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:30:01