Exit 상태 코드 사용
종료 상태 코드 (Exit status codes) 는 명령 또는 스크립트가 성공적으로 완료되었는지 여부를 나타내기 위해 반환되는 숫자 값입니다. Linux 및 Unix 계열 시스템에서:
- 종료 상태가
0이면 성공을 나타냅니다.
- 0 이 아닌 종료 상태 (1-255) 는 오류 또는 기타 예외적인 조건을 나타냅니다.
특정 조건에 따라 다른 종료 상태 코드를 사용하는 스크립트를 만들어 보겠습니다.
먼저, 새 스크립트 파일을 생성합니다.
cd ~/project
touch status_codes.sh
nano 로 파일을 엽니다.
nano status_codes.sh
다음 내용을 추가합니다.
#!/bin/bash
## Demonstrating exit status codes
## Check if a filename was provided as an argument
if [ $## -eq 0 ]; then
echo "Error: No filename provided"
echo "Usage: $0 <filename>"
## Exit with status 1 (general error)
exit 1
fi
filename=$1
## Check if the file exists
if [ ! -f "$filename" ]; then
echo "Error: File '$filename' not found"
## Exit with status 2 (file not found)
exit 2
fi
## Check if the file is readable
if [ ! -r "$filename" ]; then
echo "Error: File '$filename' is not readable"
## Exit with status 3 (permission denied)
exit 3
fi
## If we get here, everything is fine
echo "File '$filename' exists and is readable"
## Exit with status 0 (success)
exit 0
파일을 저장 (Ctrl+O, Enter) 하고 nano 를 종료합니다 (Ctrl+X).
스크립트를 실행 가능하게 만듭니다.
chmod +x status_codes.sh
이제 이 스크립트를 다양한 시나리오로 테스트해 보겠습니다.
먼저, 인자 없이 스크립트를 실행합니다.
./status_codes.sh
다음과 같은 출력을 볼 수 있습니다.
Error: No filename provided
Usage: ./status_codes.sh <filename>
스크립트는 상태 코드 1 로 종료되었습니다. 특수 변수 $?를 사용하여 마지막 명령의 종료 상태를 확인할 수 있습니다.
echo $?
다음과 같은 출력을 볼 수 있습니다.
1
이제 테스트 파일을 만들고 스크립트를 다시 실행해 보겠습니다.
echo "This is a test file" > testfile.txt
./status_codes.sh testfile.txt
다음과 같은 출력을 볼 수 있습니다.
File 'testfile.txt' exists and is readable
종료 상태를 확인합니다.
echo $?
다음과 같은 출력을 볼 수 있습니다.
0
이는 스크립트가 성공적으로 완료되었음을 나타냅니다.
마지막으로, 존재하지 않는 파일로 시도해 봅니다.
./status_codes.sh nonexistent_file.txt
다음과 같은 출력을 볼 수 있습니다.
Error: File 'nonexistent_file.txt' not found
종료 상태를 확인합니다.
echo $?
다음과 같은 출력을 볼 수 있습니다.
2
이는 다양한 유형의 오류를 나타내기 위해 서로 다른 종료 상태 코드를 사용하는 방법을 보여줍니다.