do while을 사용하여 무한 루프를 만들고 실패 시 중단하는 방법은 무엇입니까?

do while을 사용하여 무한 루프를 만들고 실패 시 중단하는 방법은 무엇입니까?

AWS AMI의 상태를 확인하고 상태가 일 때 일부 명령을 실행하려고 합니다 available. 다음은 이를 달성하기 위한 작은 스크립트입니다.

#!/usr/bin/env bash

REGION="us-east-1"
US_EAST_AMI="ami-0130c3a072f3832ff"

while :
do
      AMI_STATE=$(aws ec2 describe-images --region "$REGION" --image-ids $US_EAST_AMI | jq -r .Images[].State)

        [ "$AMI_STATE" == "available" ] && echo "Now the AMI is available in the $REGION region" && break
        sleep 10
done

첫 번째 호출이 성공하면 위 스크립트가 제대로 작동합니다. 하지만 나는 다음 시나리오에서 뭔가를 기대하고 있습니다

  • 값이 (현재 작동 중) $AMI_STATE과 같으면 루프를 중단해야 합니다."available""failed"
  • 값이 같으면 예상 값이 $AMI_STATE충족 "pending"될 때까지 루프가 계속되어야 합니다.

답변1

AMI_STATE의 값이 ... 와 같을 때 루프를 실행하고 싶으니 pending이렇게 작성하세요.

while
    AMI_STATE=$(aws ec2 describe-images --region "$REGION" --image-ids $US_EAST_AMI | jq -r .Images[].State) &&
    [ "$AMI_STATE" = "pending" ]
do
    sleep 10
done
case $AMI_STATE in
    "") echo "Something went wrong: unable to retrieve AMI state";;
    available) echo "Now the AMI is available in the $REGION region";;
    failed) echo "The AMI has failed";;
    *) echo "AMI in weird state: $AMI_STATE";;
esac

답변2

간단한 if 구성을 사용할 수 있습니다.

#!/usr/bin/env bash

region="us-east-1"
us_east_ami="ami-0130c3a072f3832ff"

while :
do
    ami_state=$(aws ec2 describe-images --region "$region" --image-ids "$us_east_ami" | jq -r .Images[].State)
    if [[ $ami_state == available ]]; then
        echo "Now the AMI is available in the $region region"
        break
    elif [[ $ami_state == failed ]]; then
        echo "AMI is failed in $region region"
        break
    fi
    sleep 10
done

여기서도 케이스를 선택하는 것이 좋습니다.

#!/usr/bin/env bash

region="us-east-1"
us_east_ami="ami-0130c3a072f3832ff"

while :
do
    ami_state=$(aws ec2 describe-images --region "$region" --image-ids "$us_east_ami" | jq -r .Images[].State)

    case $ami_state in
        available)
            echo "Now the AMI is available in the $region region"
            break
        ;;
        failed)
            echo "AMI is failed in $region region"
            break
        ;;
        pending) echo "AMI is still pending in $region region";;
        *)
            echo "AMI is in unhandled state: $ami_state"
            break
        ;;
    esac
    sleep 10
done

bash 매뉴얼에서 두 가지에 대해 모두 읽을 수 있습니다.3.2.5.2 조건부 구성

또는 무한 while 루프를 포기하고 대신 사용할 수도 있습니다.루프까지:

#!/usr/bin/env bash

region="us-east-1"
us_east_ami="ami-0130c3a072f3832ff"

until [[ $ami_state == available ]]; do
    if [[ $ami_state == failed ]]; then
        echo "AMI is in a failed state for $region region"
        break
    fi
    ami_state=$(aws ec2 describe-images --region "$region" --image-ids "$us_east_ami" | jq -r .Images[].State)
    sleep 10
done

상태를 사용할 수 있을 때까지 필요한 만큼 반복됩니다. 적절한 오류 처리가 없으면 이는 쉽게 무한 루프로 바뀔 수 있습니다. (실패 이외의 문제를 일으킬 수 있는 상태가 없는지 확인하십시오)

관련 정보