DevOps/Shell

exit

게임이 더 좋아 2023. 1. 1. 22:48
반응형
728x170

exit는 우리가 프로그래밍 할 때의 main 함수의 return과 비슷하다고 생각하면 된다.

실제로 Shell script의 끝을 지정하는 것이다.

다시 말해서 우리는 스크립트(프로세스)의 종료를 exit로 결정할 수 있다고 봐도 된다.

 

exit code의 범위는 0~255로 솔직히 맘대로 정할 수 있다. 

일반적으로는 exit code가 0이라면 정상 종료 그 외에는 비정상이라고 할 수 있다.

특히 예시를 들어주자면

  • 0: Success. The command or program completed successfully.
  • 1: General error. The command or program encountered an unspecified error.
  • 2: Misuse of shell builtins. The command or program was used incorrectly or in an unsupported way.
  • 126: Cannot execute the command. The command or program could not be run due to insufficient permissions or other issues.
  • 127: Command not found. The command or program could not be found.

 

위와 같은 약속을 한다. 

 

그건 그렇고 

우리가 exit 써야하는 경우가 있나?

2 가지가 있다.

exit code를 통해 shell script의 정상 작동 여부를 알기 위해서이다.

당연히 exit code를 통해서 작동 여부를 알 수 있다. 더욱이 0~255라면 우리가 서로 약속만 한다면 해당 스크립트의 어떤 작동 여부도 알 수 있을 것이다.

#!/bin/bash

# Perform some action
do_something

# Check the exit code of the action
if [ $? -eq 0 ]; then
    # Action was successful, exit with success code
    exit 0
else
    # Action was not successful, exit with failure code
    exit 1
fi

다른 경우는 exit code에 대한 여부를 다른 스크립트에서 실행하기 위함이다.

당연히 위와 같지만 if문이 조금 달라진다.

#!/bin/bash

# Run script A and store its exit code in a variable
exit_code=$(./script_a.sh)

# Check the exit code of script A
if [ $exit_code -eq 0 ]; then
    # Script A was successful, run script B
    ./script_b.sh
else
    # Script A was not successful, print an error message
    echo "Error: script A failed with exit code $exit_code"
fi

 

실제로 위의 exit 코드를 정말 많이 쓰니 제대로 알아두는 것이 좋다.

 

반응형
그리드형

'DevOps > Shell' 카테고리의 다른 글

zsh vs bash  (0) 2023.03.01
Null Check  (0) 2023.01.01
let [command]  (0) 2023.01.01
environment variable  (0) 2022.12.31
Bash, 쉘 스크립트 시작하기  (0) 2022.12.25