Shell oneliner自定义curl命令与if else处理

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

我正在尝试使用 curl 命令读取 url,并期望命令在解析响应 json 后根据curl 的响应退出并返回代码 0 或 1。

我尝试解析 json 响应,但值得注意的是让它在 if else 条件下工作。

URL - 本地主机:8080/health

网址的响应

{
    "db": {
        "status": "healthy"
    },
    "scheduler": {
        "fetch": "2024-03-12T04:32:53.060917+00:00",
        "status": "healthy"
    }
}

预期产出 - 如果 Scheduler.status 正常,则一个 liner cmd 返回退出代码 0,否则 1

注意 - 我不是在寻找 0 或 1 的卷曲响应,而是寻找以 0 或 1 退出的命令。

目的 - 如果我的调度程序状态不健康,我的进程将终止并从应用程序退出。

我能够解析响应消息,但值得注意的是,在响应上正确应用条件是我迄今为止所尝试的,

cmd 1:

if ((status=$(curl -s 'https://localhost:8080/health' | python -c "import sys, json; print (json.load(sys.stdin) ['scheduler'] ['status'])"))='healthy'); then exit 0; else 1;

它会抛出错误。

zsh: parse error near `='healthy''

从上面的cmd来看,这个

curl -s 'https://localhost:8080/health' | python -c "import sys, json; print (json.load(sys.stdin) ['scheduler'] ['status'])"
部分工作正常,返回(健康/不健康),同时添加条件失败。

cmd 2:

/bin/sh -c "status=$(curl -kf https://localhost:8080/health --no- progress-meter | grep -Eo "scheduler [^}]" | grep -Eo '[^{]$' | grep -Eo "status [^}]" | grep -Eo "[^:]$" | tr -d \"' | tr -d '\r' | tr -d '\ '); if [ $status=='unhealthy']; then exit 1; fi;0"

这也不起作用,但是,这部分

curl -kf https://localhost:8080/health --no- progress-meter | grep -Eo "scheduler [^}]" | grep -Eo '[^{]$' | grep -Eo "status [^}]" | grep -Eo "[^:]$" | tr -d \"' | tr -d '\r' | tr -d '\ '
工作正常,可以返回健康/不健康

我尝试了所有这些,但没有运气,不确定是否有任何使用单个命令的解决方法。

linux shell curl cmd
1个回答
0
投票

如果你可以安装jq(https://jqlang.github.io/jq/

response=$(curl -s "https://example.com/api")
status=$(echo "$response" | jq -r '.scheduler.status')

if [ "$status" == "healthy" ]; then
    echo "Scheduler is healthy."
else
    echo "Scheduler is not healthy."
fi
© www.soinside.com 2019 - 2024. All rights reserved.