터미널을 종료하지 않고 오류 처리 기능에서 쉘 스크립트를 종료합니다.

터미널을 종료하지 않고 오류 처리 기능에서 쉘 스크립트를 종료합니다.

쉘 스크립트를 작성 중입니다. 해당 쉘 스크립트는 bash터미널 내부의 쉘 에서 실행됩니다 . 여기에는 중앙 오류 처리기 기능이 포함되어 있습니다. 다음 기본 데모 스니펫을 참조하세요.

function error_exit
{
   echo "Error: ${1:-"Unknown Error"}" 1>&2
   exit 1 # This unfortunately also exits the terminal
}

# lots of lines possibly calling error_exit
cd somewhere || error_exit "cd failed"
rm * || error_exit "rm failed"
# even more lines possibly calling error_exit

오류 처리기 함수는 스크립트를 종료해야 하지만 터미널을 종료해서는 안 됩니다. 어떻게 이를 달성할 수 있나요?

답변1

스크립트 종료 시 인스턴스를 생성하려면 의 내장 기능 bash을 사용하십시오 .trapbash

trap 'bash' EXIT

에서 help trap:

trap: trap [-lp] [[arg] signal_spec ...]
    Trap signals and other events.

    Defines and activates handlers to be run when the shell receives signals
    or other conditions.

    ARG is a command to be read and executed when the shell receives the
    signal(s) SIGNAL_SPEC.  If ARG is absent (and a single SIGNAL_SPEC
    is supplied) or `-', each specified signal is reset to its original
    value.  If ARG is the null string each SIGNAL_SPEC is ignored by the
    shell and by the commands it invokes.

    If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.

따라서 를 실행하면 trap 'bash' EXITbash이 EXIT 신호를 수신할 때 가 읽고 실행됩니다. 대화형 셸을 생성하면 결과적으로 터미널이 닫히는 것을 방지하는 효과가 있습니다.

function error_exit
{
   echo "Error: ${1:-"Unknown Error"}" 1>&2
   exit 1 # This unfortunately also exits the terminal
}

trap 'bash' EXIT
# lots of lines possibly calling error_exit
cd somewhere || error_exit "cd failed"
rm * || error_exit "rm failed"
# even more lines possibly calling error_exit

관련 정보