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

如何查看所有Git分支中已变更的文件及对应分支?

解决方案

核心思路

要实现遍历所有本地分支、检测文件与服务器(远程仓库)版本的差异并输出指定格式内容,你可以通过遍历本地分支 + 对比本地分支与远程对应分支的差异 + 提取变更文件并格式化输出来完成。

具体实现方案

1. 基础命令组合

首先,用以下命令遍历所有本地分支:

git for-each-ref --format='%(refname:short)' refs/heads/

对每个分支,你需要检测两类差异:

  • 本地未提交的变更(含已暂存和未暂存):
    # 未暂存的变更文件
    git diff <branch> --name-only
    # 已暂存但未提交的变更文件
    git diff --cached <branch> --name-only
    
  • 本地分支与远程对应分支(如origin/<branch>)的差异:
    git diff origin/<branch> <branch> --name-only
    

2. 整合为自动化脚本(Shell示例)

如果要批量处理所有分支并输出指定格式,可以使用以下Shell脚本:

#!/bin/bash

# 遍历所有本地分支
for branch in $(git for-each-ref --format='%(refname:short)' refs/heads/); do
    # 检查本地未提交的变更文件
    changed_files=$(git diff $branch --name-only && git diff --cached $branch --name-only)
    if [ -n "$changed_files" ]; then
        echo "$changed_files" | while read file; do
            echo "Uncomitted changes in $file in Branch $branch"
        done
    fi

    # 检查本地分支与远程分支的差异(跳过不存在对应远程分支的本地分支)
    if git show-ref --verify --quiet refs/remotes/origin/$branch; then
        remote_changed_files=$(git diff origin/$branch $branch --name-only)
        if [ -n "$remote_changed_files" ]; then
            echo "$remote_changed_files" | while read file; do
                echo "Uncomitted changes in $file in Branch $branch"
            done
        fi
    fi
done

3. 注意事项

  • 脚本会自动跳过不存在对应远程分支的本地分支,避免触发报错。
  • 如果你的远程仓库别名不是origin,需要将脚本中的origin替换为实际的远程仓库名称。
  • 若仅需检测本地未提交的变更(暂存/未暂存),可移除脚本中远程分支对比的代码块。
  • 开发工具时,可基于此逻辑,用Python、Go等语言调用Git命令获取输出后再做格式化处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:01:42