프로그래밍/Server
[BASH] 쉘스크립트에서 try catch 와 유사하게 처리하기
웰치스짱
2023. 3. 8. 10:32
반응형
Bash에서는 try / catch가 없습니다. 다만 별도로 if 와 exit코드를 통해서 유사하게 구현은 가능합니다.
아래와 같이 if 와 exit로 구현해보겠습니다.
#!/bin/bash
# Attempt the operation
do_something_that_might_fail
# Check the exit code
if [ $? -ne 0 ]; then
# If the operation failed, handle the error
echo "An error occurred while doing something."
exit 1
fi
# If the operation succeeded, continue with the script
echo "The operation completed successfully."
위와 같이 윗단 코드에서 exit가 나오면 if then 을 통해서 에러가 있었는지 확인하고 없었으면 하단 코드를 정상적으로 실행합니다.
또한 아래와 같이 함수를 정의해서 사용할 수도 있습니다.
#!/bin/bash
function handle_error {
# Handle the error here
echo "An error occurred: $1"
exit 1
}
# Attempt the operation
do_something_that_might_fail || handle_error "Failed to do something."
# If the operation succeeded, continue with the script
echo "The operation completed successfully."
위와 같이 handle_error함수를 정의하고 좀더 간단하게 처리가 가능합니다. 이렇게 사용하면 여러 부분에서 확인이 가능할 것 입니다.
반응형