「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(、、、、developmasterと比較する方が合理的です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

関連情報