Bash 스크립트의 오류 확인

Bash 스크립트의 오류 확인

${deleteOldBranchRemote}오류가 없을 때 조건부로 실행되도록 이 스크립트를 어떻게 수정합니까 ${getRename}?

Now_hourly=$(date +%d%b%H%M)
#echo "$Now_hourly"

newrcName="rc$Now_hourly"
#rename rc to the new name
getRename="git branch -m $newrcName"
#Delete the old-name remote branch
deleteOldBranchRemote="git push origin --delete rc"
${getRename}
#if getRename has error then do not execute the following line
#if [ $noErrorSomehowIneedToCheckForErrors ]
  #then
    ${deleteOldBranchRemote}
#fi

답변1

다음과 같이 작성할 수 있습니다.

if git branch -m $newrcName; then
    git push origin --delete rc
fi

따라서 두 번째 명령은 첫 번째 명령이 종료 코드 0(성공을 나타냄)으로 끝나는 경우에만 실행됩니다.

를 실행하여 if 키워드에 대한 자세한 정보를 얻을 수 있습니다 help if. 내 시스템의 출력 예(Bash 4.3.46(1)-릴리스):

if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional.

The `if COMMANDS' list is executed.  If its exit status is zero, then the
`then COMMANDS' list is executed.  Otherwise, each `elif COMMANDS' list is
executed in turn, and if its exit status is zero, the corresponding
`then COMMANDS' list is executed and the if command completes.  Otherwise,
the `else COMMANDS' list is executed, if present.  The exit status of the
entire construct is the exit status of the last command executed, or zero
if no condition tested true.

Exit Status:
Returns the status of the last command executed.

오류 코드를 알고 싶다면 $? Bash는 이 변수에 실행된 마지막 명령의 종료 코드를 저장합니다. 나중에 사용하기 위해 변수에 저장할 수 있습니다.

git branch -m $newrcName
BRANCH_EXIT_CODE=$?
echo "git branch -m $newrcName exit code was $BRANCH_EXIT_CODE"
# $? now contains the exit code of the preceding echo
if [ $BRANCH_EXIT_CODE -eq 0 ]; then
    git push origin --delete rc
fi

관련 정보