"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

관련 정보