반응형
오류 발생 시 스크립트 종료
나는 다음이 있는 셸 스크립트를 만들고 있습니다.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
반응형
'programing' 카테고리의 다른 글
종속성 속성을 선택해야 하는 이유 (0) | 2023.04.28 |
---|---|
Wpf 텍스트 블록의 수직 텍스트 (0) | 2023.04.28 |
MVC3에서 Azure Blob 파일 다운로드하기 (0) | 2023.04.28 |
레이블에 "_" 문자가 표시되지 않음 (0) | 2023.04.28 |
워크시트_변경 하위 절차 중에 MS Excel이 충돌하고 닫히는 이유는 무엇입니까? (0) | 2023.04.28 |