首页 > 解决方案 > 使用 curl 命令上的“jq”输出作为 while 循环中的条件

问题描述

我希望此语句在此 api 响应中的 json 字段的值为 null 时继续循环。

while $(curl --location --request GET "https://example.com/integration-test/results/json"| jq '.result') == null
    do
    echo "Waiting for Integration tests to finish. Trying again in 10 seconds."
    sleep 2
done

显然不起作用,== null但它说明了我的目标。当集成测试完成时,此 api 调用将在“结果”中返回 SUCCESS 或 FAILURE。那是我希望循环停止的时候。

标签: bashcurl

解决方案


考虑使用-e参数使其退出状态反映其输出(当唯一的输出orjq时发出失败的退出状态)。 nullfalse

为了清晰而不是简洁而编写下面的代码(使用显式分组运算符来明确否定适用于整个管道):

#!/usr/bin/env bash
set -o pipefail  # make a failure on the left-hand side fail the entire pipeline
while ! { curl --fail -L "https://example.com/integration-test/results/json" \
          | jq -e '.result' >/dev/null; }; do
    echo "Waiting for Integration tests to finish. Trying again in 10 seconds."
    sleep 10
done

推荐阅读