쉘 스크립트의 if 블록에서 종료는 무엇을 합니까?

쉘 스크립트의 if 블록에서 종료는 무엇을 합니까?

유닉스 쉘 스크립트에 관해 질문이 있습니다.

exit 1내부적으로 실행한다고 가정하면 if종료되나요, 아니면 계속 외부에서 실행되나요 if? 아래는 가상의 예입니다.

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
    if [ "$PASSWORD" -gt 10]; then
        echo "password is too large!"
        exit 1
    fi
    echo "You have access!"
    exit 1
fi

답변1

exit호출 프로세스를 종료합니다. 대부분의 경우 루프, 함수 또는 포함된 스크립트 내에서 호출하더라도 전체 스크립트가 종료됩니다. "캡처된" 유일한 쉘 구성은 exit하위 쉘을 도입하는 구성입니다(예:두 갈래로 갈라진서브쉘 프로세스):

  • (…)서브쉘에서 괄호 안의 명령을 실행하기 위한 기본 서브쉘 구조.
  • 명령을 실행하고 해당 출력을 문자열로 반환하는 명령 대체 구조 $(…)(및 더 이상 사용되지 않는 해당 기능인 backtick )`…`
  • 백그라운드 작업이 분기되었습니다 &.
  • 왼쪽관로 |및 대부분의 쉘의 오른쪽(ATT ksh 및 zsh 제외)
  • 일부 쉘에는 ksh, bash 및 zsh의 프로세스 대체 등과 같은 추가 하위 프로세스 구조가 있습니다 <(…).>(…)

while키워드를 사용하여 루프 for를 중단 break하거나 키워드를 사용하여 함수를 중단할 수 있습니다 return.

답변2

exit일반적으로 쉘이 내장되어 있으므로 이론적으로는 사용하는 쉘에 따라 다릅니다. 그러나 현재 프로세스를 종료하는 것 이외의 쉘이 어디에서 실행되는지는 알 수 없습니다. Bash 매뉴얼 페이지에서,

   exit [n]
          Cause the shell to exit with a status of n.  If  n  is  omitted,
          the exit status is that of the last command executed.  A trap on
          EXIT is executed before the shell terminates.

따라서 단순히 현재 if절을 종료하는 것이 아니라 전체 셸(또는 프로세스, 본질적으로 스크립트가 셸 프로세스에서 실행 중이기 때문에 프로세스)을 종료합니다.

맨 쉬에서,

 exit [exitstatus]
        Terminate the shell process.  If exitstatus is given it is used as
        the exit status of the shell; otherwise the exit status of the
        preceding command is used.

마지막으로 man ksh에서,

   † exit [ n ]
          Causes  the  shell  to exit with the exit status specified by n.
          The value will be the least significant 8 bits of the  specified
          status.   If  n  is omitted, then the exit status is that of the
          last command executed.  An end-of-file will also cause the shell
          to  exit  except for a shell which has the ignoreeof option (see
          set below) turned on.

답변3

exit스크립트가 완전히 종료됩니다.

break루프에서는 한 수준 위로 올라가지만 if 문에서는 그렇지 않습니다(내 bash 매뉴얼 페이지에 따르면).

관련 정보