development

명령이 실패한 경우 종료하는 방법?

big-blog 2020. 5. 14. 20:32
반응형

명령이 실패한 경우 종료하는 방법?


나는 쉘 스크립팅의 멍청한 놈입니다. 명령이 실패하면 메시지를 인쇄하고 스크립트를 종료하고 싶습니다. 난 노력 했어:

my_command && (echo 'my_command failed; exit)

그러나 작동하지 않습니다. 스크립트에서이 줄 다음에 나오는 지침을 계속 실행합니다. 우분투와 bash를 사용하고 있습니다.


시험:

my_command || { echo 'my_command failed' ; exit 1; }

네 가지 변경 사항 :

  • 변경 &&||
  • { }대신 사용( )
  • ;소개exit
  • 후 구역 {및 이전}

당신이 메시지와 명령 (아닌 값으로 종료) 실패 할 경우에만 종료를 인쇄 할 때문에 당신은 필요가 ||아닌를 &&.

cmd1 && cmd2

성공하면 실행 cmd2됩니다 cmd1(exit value 0). 어디로

cmd1 || cmd2

실패하면 실행 cmd2됩니다 cmd1(종료 값이 0이 아님).

를 사용 ( )하면 내부 명령이 하위 셸 에서 실행되고 exit거기에서 a 호출하면 원래 셸이 아닌 하위 셸이 종료되므로 원래 셸에서 계속 실행됩니다.

이 사용을 극복하기 위해 { }

마지막 두 가지 변경 사항은 bash에 필요합니다.


다른 답변은 직접 질문을 잘 다루었지만을 사용하는 데 관심이있을 수 있습니다 set -e. 이를 통해 if테스트 와 같은 특정 컨텍스트 이외의 명령이 실패 하면 스크립트가 중단됩니다. 특정 스크립트의 경우 매우 유용합니다.


스크립트의 모든 명령에 대해 해당 동작을 원하면 추가하십시오.

  set -e 
  set -o pipefail

스크립트의 시작 부분에. 이 옵션 쌍은 명령이 0이 아닌 종료 코드와 함께 리턴 될 때마다 bash 인터프리터에게 종료하도록 지시합니다.

그래도 종료 메시지를 인쇄 할 수 없습니다.


또한 각 명령의 종료 상태는 쉘 변수 $?에 저장되며 명령 실행 후 즉시 확인할 수 있습니다. 0이 아닌 상태는 실패를 나타냅니다.

my_command
if [ $? -eq 0 ]
then
    echo "it worked"
else
    echo "it failed"
fi

다음 관용구를 해킹했습니다.

echo "Generating from IDL..."
idlj -fclient -td java/src echo.idl
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi

echo "Compiling classes..."
javac *java
if [ $? -ne 0 ]; then { echo "Failed, aborting." ; exit 1; } fi

echo "Done."

각 명령 앞에 정보 에코를 사용하고 각 명령 뒤에 동일한
if [ $? -ne 0 ];...행을 사용하십시오. 물론 원하는 경우 해당 오류 메시지를 편집 할 수 있습니다.


제공은 my_commandcanonically, 설계 즉, 성공하면 그 다음, 0을 반환 &&정확하게 당신이 원하는 것을 반대입니다. 당신은 원합니다 ||.

또한 (bash에서 나에게 옳지 않은 것처럼 보이지만 내가있는 곳에서 시도 할 수는 없습니다. 말해.

my_command || {
    echo 'my_command failed' ;
    exit 1; 
}

종료 오류 상태를 유지하고 한 줄에 하나의 명령으로 읽을 수있는 파일이있는 경우에도 사용할 수 있습니다.

my_command1 || exit $?
my_command2 || exit $?

This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.


The trap shell builtin allows catching signals, and other useful conditions, including failed command execution (i.e., a non-zero return status). So if you don't want to explicitly test return status of every single command you can say trap "your shell code" ERR and the shell code will be executed any time a command returns a non-zero status. For example:

trap "echo script failed; exit 1" ERR

Note that as with other cases of catching failed commands, pipelines need special treatment; the above won't catch false | true.


The following functions only echoes errors if a command fails:

silently () {
    label="${1}"
    command="${2}"
    error=$(eval "${command}" 2>&1 >"/dev/null")

    if [ ${?} -ne 0 ]; then
        echo "${label}: ${error}" >&2
        exit 1
    fi
}

참고URL : https://stackoverflow.com/questions/3822621/how-to-exit-if-a-command-failed

반응형