【问题标题】:Wait until a condition is met in bash script等到在 bash 脚本中满足条件
【发布时间】:2022-01-12 19:10:00
【问题描述】:
until [ $(aws ssm get-automation-execution --automation-execution-id "$id" --query 'AutomationExecution.AutomationExecutionStatus' --output text) = *"InProgress"* ];
do
  echo "Automation is running......"
  sleep 1m
done
status=$(aws ssm get-automation-execution --automation-execution-id "$id" --query 'AutomationExecution.AutomationExecutionStatus' --output text)
if [ "$status" == "Success" ]; then
    echo "Automation $status"
elif [ "$status" == "Failed" -o "$status" == "Cancelled" -o "$status" == "Timed Out" ]; then
    echo "Automation $status"
fi

这里的循环永远不会退出, 即使在执行自动化并且状态不是进行中后,它也会继续打印“自动化正在运行......” 我想做的是等到状态为“进行中”,在屏幕上打印“自动化正在运行......”。 完成后,如果失败或成功,我想在屏幕上打印自动化状态。

【问题讨论】:

  • 您只是在比较字符串。 aws... 命令未执行
  • 使用$(aws ssm ....) 代替双引号。
  • 我补充说循环它仍然没有退出
  • *"InProgress"* 周围尝试通配符,一些命令会在其输出中打印回车符或换行符。也只使用一个= 符号。
  • 不应该反过来,while 而不是until?如果命令快速完成,您可能永远看不到该字符串,并且您希望在它运行时等待,而不是直到它运行。

标签: bash shell aws-cli ssm aws-ssm


【解决方案1】:

添加 if else until 帮助我摆脱了循环。

until [ $(aws ssm get-automation-execution --automation-execution-id "$id" --query 'AutomationExecution.AutomationExecutionStatus' --output text) = *"InProgress"* ];
do
  echo "Automation is running......"
  sleep 10s
  if [ $(aws ssm get-automation-execution --automation-execution-id "$id" --query 'AutomationExecution.AutomationExecutionStatus' --output text) != "InProgress" ]; then
     echo "Automation Finished"
     status=$(aws ssm get-automation-execution --automation-execution-id "$id" --query 'AutomationExecution.AutomationExecutionStatus' --output text)
     echo "Automation $status"
     if [$status != "Success"]; then
        exit 3
        echo "Automation $status"
     fi   
    break
  fi
done

【讨论】:

    【解决方案2】:

    这是我使用的通用函数:

    function wait_for() {
        timeout=$1
        shift 1
        until [ $timeout -le 0 ] || ("$@" &> /dev/null); do
            echo waiting for "$@"
            sleep 1
            timeout=$(( timeout - 1 ))
        done
        if [ $timeout -le 0 ]; then
            return 1
        fi
    }
    

    你可以有另一个检查条件的函数:

    function is_still_running() {
        aws_status=$(aws ssm get-automation-execution --automation-execution-id "$id" --query 'AutomationExecution.AutomationExecutionStatus' --output text)
        if [ "${aws_status}" = *"InProgress"* ]; then
            return 0;
        else
            return 1;
        fi
    }
    

    那么用法是:

    wait_for 100 is_still_running
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 2018-08-09
      • 2018-09-29
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多