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

Windows批处理脚本:移除Git ls-remote哈希值以实现旧分支版本比较

移除git ls-remote返回的哈希值,修复Windows批处理的版本比较功能

我正在基于GitFlow编写Windows批处理脚本,用于删除Git远程仓库中的旧release分支:用户输入指定release分支后,脚本会删除所有版本号更早的远程release分支(目前仅用echo做测试)。"旧分支"由分支名中/后的版本号判定,例如release/1.15。当前脚本仅支持1.xx系列的release分支,但遇到了问题:git ls-remote命令会同时返回分支的哈希值,我无法将其从变量中移除,导致版本比较功能无法正常工作。

当前使用的脚本:

@echo off
setlocal enabledelayedexpansion

set /p CUTOFF_BRANCH=Enter the name of the release branch:
set CUTOFF_BRANCH_VERSION=!CUTOFF_BRANCH:release/1.=!

for /f "tokens=*" %%a in ('git ls-remote --heads origin "release/*"') do (
    set BRANCH_REF=%%a
    set BRANCH_NAME=!BRANCH_REF:refs/heads/=!
    set BRANCH_NAME_VERSION=!BRANCH_NAME:release/1.=!
    echo !CUTOFF_BRANCH_VERSION!   !BRANCH_NAME_VERSION! >> output.txt
    if "%BRANCH_NAME_VERSION%" lss "%CUTOFF_BRANCH_VERSION%" (
        echo ref !BRANCH_REF! >> output.txt
        echo deleting !BRANCH_NAME! >> output.txt
    )
)
echo All older release branches have been deleted.

pause

output.txt部分内容:

120   f16eed16b2a101cd06b106f2ac81af85199609d4     0 
120   7045e4dd3171d93c47c4f5cc8cb30c4fe19d50a5     1 
...

核心修复思路

git ls-remote --heads的输出格式是哈希值 + 分支引用路径,直接通过for /f的tokens参数跳过哈希值,提取分支部分即可,无需后续字符串替换处理哈希。同时要修正循环内延迟变量的引用方式。

修改后的脚本

@echo off
setlocal enabledelayedexpansion

set /p CUTOFF_BRANCH=Enter the name of the release branch:
set CUTOFF_BRANCH_VERSION=!CUTOFF_BRANCH:release/1.=!

:: 使用tokens=2-*跳过哈希值,直接获取分支引用路径(refs/heads/release/xxx)
for /f "tokens=2-*" %%a in ('git ls-remote --heads origin "release/*"') do (
    set BRANCH_REF=%%a
    set BRANCH_NAME=!BRANCH_REF:refs/heads/=!
    set BRANCH_NAME_VERSION=!BRANCH_NAME:release/1.=!
    echo !CUTOFF_BRANCH_VERSION!   !BRANCH_NAME_VERSION! >> output.txt
    :: 循环内的延迟变量要用!包裹,不能用%
    if !BRANCH_NAME_VERSION! lss !CUTOFF_BRANCH_VERSION! (
        echo ref !BRANCH_REF! >> output.txt
        echo deleting !BRANCH_NAME! >> output.txt
    )
)
echo All older release branches have been deleted.

pause

关键修改点

  • 跳过哈希值:for /f "tokens=2-*"表示提取输出中的第2个及以后的所有内容,%%a直接拿到refs/heads/release/xxx这样的分支引用路径,彻底规避哈希值的干扰。
  • 修正变量引用:循环内部的变量比较必须用!BRANCH_NAME_VERSION!和!CUTOFF_BRANCH_VERSION!,因为启用了延迟变量扩展,用%会导致变量只在循环初始化时解析,无法获取循环内的实时值。

内容的提问来源于stack exchange,提问作者marek.vidlak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:07:04