卷曲,分裂字符串,并在需要时退出

时间:2018-12-04 14:07:50

标签: bash split

这是运行curl --silent localhost:9091/health

时的输出
# HELP metrics_qollector_ttt_health_check The status of ttt.
# TYPE metrics_qollector_ttt_health_check gauge
metrics_qollector_ttt_health_check 1.0
# HELP metrics_qollector_database_health_check The status of the database.
# TYPE metrics_qollector_database_health_check gauge
metrics_qollector_database_health_check 1.0
# HELP metrics_qollector_health_checks_latency_seconds Health check latency in seconds.
# TYPE metrics_qollector_health_checks_latency_seconds summary
metrics_qollector_health_checks_latency_seconds_count{method="runtime",} 1.0
metrics_qollector_health_checks_latency_seconds_sum{method="runtime",} 9.51166E-4

我需要煮沸一个bash脚本来检查metrics_qollector_ttt_health_check == "1.0"还是metrics_qollector_database_health_check == "1.0",然后是exit 0;,否则是exit 1;

我一直想做的是以下

#!/usr/bin/env bash

set -e

HEALTHSTATUS=$(curl --silent localhost:9091/health)

for item in ${HEALTHSTATUS}
    if [[ item[0] = "metrics_qollector_ttt_health_check" && item[1] = "1.0" ]  || [ item[0] = "metrics_qollector_database_health_check" && item[1] "1.0" ]]; then
        exit 0;
    else
        exit 1;
done

2 个答案:

答案 0 :(得分:1)

如果找到匹配项,则

grep -q以状态0退出,如果没有匹配项,则以状态1存在。您可以用以下单行代码替换整个脚本:

curl --silent localhost:9091/health |
grep -Eq '^metrics_qollector_(ttt|database)_health_check 1\.0$'

答案 1 :(得分:1)

您有这么多种方法,但这是其中一种:

#!/bin/bash

STATUS=$(curl --silent http://localhost:9091/health | egrep "^metrics_qollector_ttt_health_check |^metrics_qollector_database_health_check ")

EXIT_STATUS=$(echo $STATUS | awk '{if(NF == 4) { if(($2 == 0) || ($4 == 0)) {print "0"} else {print "1"} } else {print "2"}}')

exit $EXIT_STATUS

awk应该将浮点值(1.0)解析为数值以进行比较。它还会检查您是否同时拥有两个指标。

脚本退出代码

0-至少一个值为0.0

1-所有值都不为0.0

2-如果由于某种原因您没有一个或两个指标     健康API