Shell一行命令自定义curl指令及if else处理
我想用curl命令来读取一个网址,并希望根据curl的响应来判断命令的返回码是0还是1,具体是解析响应的json数据后得出的结果。
我尝试解析json响应,但在if else条件中没法正常工作。
网址 - localhost:8080/health
这个网址的响应内容是
{
"db": {
"status": "healthy"
},
"scheduler": {
"fetch": "2024-03-12T04:32:53.060917+00:00",
"status": "healthy"
}
}
期望的输出 - 一行命令,如果scheduler.status是健康的就返回0,否则返回1
注意 - 我不是想要curl的响应是0或1,而是想要命令的返回码是0或1。
目的 - 如果我的调度器状态不健康,那么我的进程就会终止并退出应用。
我能解析响应消息,但在条件应用上遇到问题,以下是我到目前为止尝试的内容:
命令 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''
从上面的命令来看,这部分curl -s 'https://localhost:8080/health' | python -c "import sys, json; print (json.load(sys.stdin) ['scheduler'] ['status'])"
是正常工作的,可以返回(healthy/unhealthy),但加上条件就失败了。
命令 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 '\ '
是正常的,可以返回healthy/unhealthy。
我尝试了这些,但都没有成功,不确定是否有办法用一条命令解决。
如果能用shell实现那就太好了,如果不行,用python也可以。
请注意 - 不需要安装Jq或其他工具,只用现有的命令即可
8 个回答
你可以把比较的部分放到Python脚本里面。
curl -s 'https://localhost:8080/health' |
python -c 'import sys, json; sys.exit(json.load(sys.stdin)["scheduler"]["status"]) != "healthy")'; then
不需要用if
语句;如果这是你脚本中的最后一条(或者唯一的)命令,那么它的退出状态就是整个脚本的退出状态。
我认为jq
是处理这个问题的合适工具,而所提供的awk
解决方案则比较脆弱...
$status=$(curl -kf https://localhost:8080/health --no- progress-meter | awk 'BEGIN{RS="\n \"";FS="\n"}$1~/scheduler/&&$3!~/healthy/{exit 1}')
当你确定你的健康变量中没有 '}' 这个符号时,你可以使用下面的代码:
curl -s 'https://localhost:8080/health' | tr -d '\n' | grep -Eq '"scheduler": [^}]*"healthy"'