While 语句和条件行为

问题描述 投票:0回答:1

我有一个非常简单的脚本,它尝试检查 API 调用的状态最多五次,每次尝试之间暂停一秒钟。脚本模拟 API 调用,通过将响应变量设置为 400 来检查状态。如果响应为 200,它将 stop 变量设置为“true”并打印成功消息。否则,它会打印一条带有响应代码的失败消息。

      counter=0
      max_attempts=5
      stop=false

      while [ $stop = "false" ] && [ $counter -lt $max_attempts ]; do
        echo "Attempt $((counter + 1))"

        # Simulate API call to check status
        response=400

        if [ "$response" = "200" ]; then
          stop=true
          echo "Call is successful."
        else
          echo "Call failed with response code: $response"
        fi

        ((counter++))
        sleep 1 
      done

      if [ "$stop" = "true" ]; then
        echo "stop is true, exiting loop."
      else
        echo "Reached maximum attempts, exiting loop."
      fi

我不明白为什么在第一次迭代后停止

| Attempt 1
| Call failed with response code: 400
bash loops shell while-loop conditional-statements
1个回答
0
投票

在@CharlesDuffy的帮助下解决了这个问题

      counter=0
      max_attempts=5
      stop=false
    
      while [ $stop = "false" ] && [ $counter -lt $max_attempts ]; do
        echo "Attempt $((counter + 1))"
        
        # Simulate API call to check status
        response=400
        
        if [ "$response" = "200" ]; then
          stop=true
          echo "Call is successful."
        else
          echo "Call failed with response code: $response"
        fi
        
        counter=$((counter+1))
        sleep 1
      done
    
      if [ "$stop" = "true" ]; then
        echo "stop is true, exiting loop."
      else
        echo "Reached maximum attempts, exiting loop."
      fi
© www.soinside.com 2019 - 2024. All rights reserved.