[bash] 오류 발생시 스크립트 종료

다음 if과 같은 기능 을 가진 쉘 스크립트를 작성 중입니다.

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables
fi

...

오류 메시지가 표시된 후 스크립트 실행이 완료되기를 원합니다. 어떻게해야합니까?



답변

찾고 exit있습니까?

이것은 가장 좋은 배쉬 가이드입니다.
http://tldp.org/LDP/abs/html/

문맥:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
    exit 1 # terminate and indicate error
fi

...


답변

set -e스크립트 를 넣으면 스크립트는 명령이 실패하자마자 (즉, 명령이 0이 아닌 상태를 반환하는 즉시) 종료됩니다. 이것은 당신이 당신의 자신의 메시지를 쓸 수 없지만 종종 실패한 명령의 자신의 메시지로 충분합니다.

이 방법의 장점은 자동이라는 것입니다. 오류 사례를 잊어 버릴 위험이 없습니다.

그 상태 (예 : 조건에 따라 시험 할 때, 명령 if, &&또는 ||) 스크립트를 종료하지 않습니다는 (다른 조건은 무의미). 실패가 중요하지 않은 간헐적 인 명령에 대한 관용구는 command-that-may-fail || true입니다. set -e을 사용하여 스크립트의 일부를 끌 수도 있습니다 set +e.


답변

당신이 맹목적으로 종료 대신 사용하는 대신 오류를 처리 할 수 있도록하려면 set -e,를 사용 trap상의 ERR의사 신호.

#!/bin/bash
f () {
    errorCode=$? # save the exit code as the first thing done in the trap function
    echo "error $errorCode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errorCode  # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff

다른 트랩은 일반적인 유닉스 신호 플러스 다른 배쉬 의사 신호를 포함하여 다른 신호를 처리하도록 설정할 수 있습니다 RETURNDEBUG.


답변

방법은 다음과 같습니다.

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE ***
************
'


답변

exit 1당신이 필요한 전부입니다. 은 1당신이 원하는 경우에, 말, 변경할 수 있도록 반환 코드 1성공적인 실행을 의미하고 -1그런 오류 또는 무언가를 의미 할 수 있습니다.


답변