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

Bash脚本检查Git main分支报错,求排查解决方法

问题原因与解决办法
  • 报错根源:if判断行的语法错误——双中括号[[和后续表达式之间缺少空格。bash会把[["$branch"识别成一个不存在的命令,因此抛出[[main: command not found错误。
  • main无需转义:这里的main只是普通字符串,没有特殊语法含义,完全不需要转义处理。

修正后的核心代码片段

# 原错误行
# if [["$branch" != "main"]]; then

# 修正后(注意[[ 后面、]]前面的空格)
if [[ "$branch" != "main" ]]; then
    git switch main
fi

额外优化建议

  • 切换分支前可以先检查main分支是否存在,避免切换失败:
    if [[ "$branch" != "main" ]]; then
        if git show-ref --verify --quiet refs/heads/main; then
            git switch main
        else
            echo "main分支不存在,跳过切换"
        fi
    fi
    
  • 进入仓库目录时增加错误检查,避免路径不存在时后续命令报错:
    cd "$repo" || { echo "无法进入仓库目录:$repo"; continue; }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:34:53