programing

오류 발생 시 스크립트 종료

powerit 2023. 4. 28. 21:44
반응형

오류 발생 시 스크립트 종료

나는 다음이 있는 셸 스크립트를 만들고 있습니다.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

...

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

스크립트를 입력하면 스크립트 내부의 명령이 실패하는 즉시(즉, 명령이 0이 아닌 상태를 반환하는 즉시) 종료됩니다.이렇게 하면 사용자가 직접 메시지를 작성할 수는 없지만 실패한 명령의 자체 메시지로 충분한 경우가 많습니다.

이 접근 방식의 장점은 자동이라는 것입니다. 오류 사례를 처리하는 것을 잊어버릴 위험이 없습니다.

조건부로 상태를 테스트하는 명령(예:if,&&또는||) 스크립트를 종료하지 않습니다(조건이 무의미할 경우).실패가 중요하지 않은 가끔의 명령어에 대한 관용구는 다음과 같습니다.command-that-may-fail || true또한 회전할 수 있습니다.set -e의 대본의 일부를 위해.set +e.

찾으십니까?

이것이 최고의 배시 가이드입니다.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을 사용합니다.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

일반적인 Unix 신호와 다른 Bash 유사 신호를 포함하여 다른 신호를 처리하도록 다른 트랩을 설정할 수 있습니다.RETURN그리고.DEBUG.

방법은 다음과 같습니다.

#!/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 *** 
************
'

언급URL : https://stackoverflow.com/questions/4381618/exit-a-script-on-error

반응형