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

如何递归识别存在可拉取远程更新的Git仓库

递归查找存在未拉取远程更新的Git仓库脚本

下面是一个符合需求的bash脚本,它会递归遍历指定根目录下的所有子目录,识别出存在未拉取远程更新的Git仓库,仅输出这类仓库的路径,不会执行拉取操作:

#!/bin/bash

# 遍历当前目录下的所有子目录(递归)
find . -type d -name ".git" | while read git_dir; do
    # 获取Git仓库的根目录(去掉/.git后缀)
    repo_dir=$(dirname "$git_dir")
    # 进入仓库目录
    cd "$repo_dir" || continue

    # 静默刷新远程仓库信息,确保本地有最新的远程分支引用
    git fetch --quiet

    # 获取当前本地分支名
    local_branch=$(git rev-parse --abbrev-ref HEAD)
    # 对应的远程分支(默认是origin/${local_branch})
    remote_branch="origin/${local_branch}"

    # 检查远程分支是否存在
    if git show-ref --verify --quiet "refs/remotes/${remote_branch}"; then
        # 计算远程分支比本地分支多的提交数
        unpulled_count=$(git rev-list --count "${local_branch}..${remote_branch}")
        if [ "$unpulled_count" -gt 0 ]; then
            # 输出仓库的绝对路径
            realpath "$repo_dir"
        fi
    fi

    # 返回上级目录,继续遍历
    cd - > /dev/null
done

脚本说明:

  • 递归定位Git仓库:通过find . -type d -name ".git"找到所有Git仓库的核心目录,再推导仓库根路径
  • 稳定的状态检查:每次检查前执行git fetch --quiet,刷新本地的远程分支引用,确保每次脚本执行都基于最新的远程状态,避免本地缓存导致输出不一致
  • 分支差异判断:用git rev-list --count HEAD..origin/分支名统计远程分支有但本地分支没有的提交数,数值大于0则说明存在未拉取更新
  • 清晰路径输出:通过realpath输出仓库绝对路径,方便直接定位

使用方法:

  1. 将上述代码保存为check-unpulled-repos.sh
  2. 赋予执行权限:chmod +x check-unpulled-repos.sh
  3. 切换到你的仓库根目录,执行脚本:./check-unpulled-repos.sh

注意事项:

  • 脚本默认使用origin作为远程仓库别名,若你的远程仓库别名不同,需修改remote_branch变量
  • 无对应远程分支的本地分支,脚本会自动忽略,不会纳入输出

内容的提问来源于stack exchange,提问作者Prof.Chaos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:42:15