将“if”条件移至变量

将“if”条件移至变量

我正在编写 git hook 文件。我有以下条件:

current_branch_name=$(echo $(git branch | grep "*" | sed "s;* ;;"))
merged_branch_name=$(echo $(git reflog -1) | cut -d" " -f 4 | sed "s;:;;")
release_branch_name="release"
develop_branch_name="develop"
master_branch_name="master"
hotfix_branch_name="hotfix/*"

if [[ ($current_branch_name == $release_branch_name  && $merged_branch_name == $develop_branch_name) 
        || ($current_branch_name == $master_branch_name && $merged_branch_name == $hotfix_branch_name) ]] ; then
#do something
fi

我想将条件从if语句移到变量中。我已经搞定了:

current_branch_name=$(echo $(git branch | grep "*" | sed "s;* ;;"))
merged_branch_name=$(echo $(git reflog -1) | cut -d" " -f 4 | sed "s;:;;")
release_branch_name="release"
develop_branch_name="develop"
master_branch_name="master"
hotfix_branch_name="hotfix/*"
is_merge_from_develop_to_release=$(($current_branch_name == $release_branch_name  && $merged_branch_name == $develop_branch_name))
is_merge_from_hotfix_to_master=$(($current_branch_name == $master_branch_name && $merged_branch_name == $hotfix_branch_name))

if [[ $is_merge_from_develop_to_release || $is_merge_from_hotfix_to_master ]] ; then
#do something
fi

它给了我一个错误hotfix/*,但如果整个条件都填充在if语句中,它就会起作用。如何正确地将条件与 解耦if

编辑(最终版本):

function checkBranches {
    local current_branch=$(echo $(git branch | grep "*" | sed "s;* ;;"))
    local merged_branch=$(echo $(git reflog -1) | cut -d" " -f 4 | sed "s;:;;")
    hotfix_branch_name="hotfix/*"

    [[ $current_branch == "release"  && 
        $merged_branch == "develop" ]] && return 0
    [[ $current_branch == "master" &&
        $merged_branch == $hotfix_branch_name ]] && return 0
    return 1
}

if checkBranches ; then
#do something
fi

答案1

并没有真正节省你的线路,但你可以使用一个函数:

check_branch () {
    local current_branch=$(echo $(git branch | grep "*" | sed "s;* ;;"))
    local merged_branch=$(echo $(git reflog -1) | cut -d" " -f 4 | sed "s;:;;")
    local release_branch_name="release"
    local develop_branch_name="develop"
    local master_branch_name="master"
    local hotfix_branch_name="hotfix/*"
    [[ "$current_branch" == "$release_branch_name"  && 
        "$merged_branch" == "$develop_branch_name" ]] && return 0
    [[ "$current_branch" == "$master_branch_name" &&
        "$merged_branch" == "$hotfix_branch_name" ]] && return 0
    return 1
}

if check_branch; then
    #something
fi

你们的分行名称会经常更改吗?如果不是,那么将变量与字符串进行比较会更有意义:release, develop, master, hotfix/*

答案2

可以$(( ))进行算术运算,但不能进行字符串比较。

一般来说,您可以转换

if cmd; then ...

var=$(cmd; echo $?)
if [[ $var ]]; then

这将执行cmd,然后回显 的返回状态cmd,并将其分配给var

答案3

case $(git branch   |sed -nes/*\ //p
)$(    git -reflog 1|cut -d\  -f4
)  in      release:develop\
|          master:hotfix/*\
)          : hooray!
esac

相关内容