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함수를 정의하고 좀더 간단하게 처리가 가능합니다. 이렇게 사용하면 여러 부분에서 확인이 가능할 것 입니다.
[AWS] S3 파일 전체 백업하기 (0) | 2023.03.27 |
---|---|
[AWS] AWS Credential Profile설정으로 여러개 사용하기 (0) | 2023.03.27 |
[AWS] EC2 파일 시스템 용량 늘리기 (0) | 2023.03.09 |
[AWS ECR] Dockerfile에서 Public AWS ECR 사용하기 (0) | 2023.03.08 |
MariaDB 여러 인스턴스 한서버에 띠우기 (0) | 2023.02.23 |
댓글 영역