You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

目标字符串含引号时[[ ]]内字符串比较失效导致循环不终止问题

问题根因

AWS CLI 的 --query 参数默认返回JSON格式的结果,你获取到的 stack_status 变量实际值是带双引号的 "CREATE_COMPLETE",而循环判断条件中比对的是无引号的 CREATE_COMPLETE,两个字符串内容不匹配,因此循环永远无法触发退出条件。

解决方案

你可以任选以下任意一种方式修复:

  • 方案1:在AWS CLI调用中增加 --output text 参数,直接返回无格式的纯文本结果,自动去掉外层引号
    stack_status=""
    while [[ $stack_status != "CREATE_COMPLETE" ]]; 
    do
       stack_status=$(aws cloudformation --region us-east-2 describe-stacks --stack-name ${stack_name} --query Stacks[0].StackStatus --output text);   
       echo "Waiting for stack to complete"; 
       echo $stack_status;   
       sleep 5;
    done
    
  • 方案2:修改判断条件,匹配带引号的字符串
    # 注意内层双引号需要转义,或者用单引号包裹目标字符串
    while [[ $stack_status != '"CREATE_COMPLETE"' ]]; 
    do
      # 原有逻辑不变
    done
    
  • 方案3:获取到结果后手动移除字符串中的双引号
    stack_status=$(aws cloudformation --region us-east-2 describe-stacks --stack-name ${stack_name} --query Stacks[0].StackStatus);   
    # 移除变量中所有双引号
    stack_status=${stack_status//\"/}
    

内容的提问来源于stack exchange,提问作者Timothy Pulliam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:45:09