Bash 脚本检查 Git 主分支出错

问题描述 投票:0回答:1

我编写了一个脚本来自动更新我的 git 存储库。

它一直有效,直到我添加了一个检查当前分支是否是

main
分支。

此时,脚本在

if
守卫的电话线上爆炸了:

[[主要:找不到命令

脚本是:

#!/bin/bash

api='/C/Repos/me/services/api'

declare -a reposArray=($api)

for repo in "${reposArray[@]}"
do
    echo
    echo "updating $repo"
    cd $repo
    echo "fetching code"
    #git fetch --prune
    
    branch="$(git branch --show-current)"
    
    if [["$branch" != "main"]]; then
        git switch main
    fi  
    
    echo "merging remote into main"
    git merge
done

知道出了什么问题吗?

main
是否具有特殊含义,需要转义?
我该如何逃避这样的整个词?

干杯

bash git-bash
1个回答
0
投票
The issue in your script is due to the syntax error in the if statement. The correct syntax for comparing strings in Bash requires spaces between the brackets and the condition. Additionally, you should use quotes around variables to prevent issues with spaces or special characters.

#!/bin/bash
    
    api='/C/Repos/me/services/api'
    
    declare -a reposArray=($api)
    
    for repo in "${reposArray[@]}"
    do
        echo
        echo "updating $repo"
        cd "$repo"
        echo "fetching code"
        #git fetch --prune
        
        branch="$(git branch --show-current)"
        
        if [ "$branch" != "main" ]; then
            git switch main
        fi  
        
        echo "merging remote into main"
        git merge
    done

我在 if 语句中的 [ 和 ] 周围添加了空格,并在变量 $branch 周围添加了引号。这应该可以解决您遇到的“命令未找到”错误。

© www.soinside.com 2019 - 2024. All rights reserved.