如何grep响应以确定有多少呼叫超时?

时间:2016-03-18 23:10:43

标签: linux bash shell curl grep

我有一个curl命令正在调用我们的服务之一,所以如果我的服务超时,它会返回如下的JSON响应:

[{"results":{"response":null},"error":{"errorCode":1001,"message":"Service Timeout","status":"FAILURE"}}]

下面是我的curl命令,当我运行时,如果有任何超时,我会得到以上响应

curl --header "Authorization: Bearer some token here" "http://localhost:8080/v2/line?&clientid=120";

我在for循环中运行我的上面的curl命令x次。现在,我想通过检查JSON响应中的"message"来查看有多少次调用已超时?我的意思是,如果我拨打了100万个电话,那么有多少电话是超时的,超时的百分比是多少?

所以我得到了一行for循环,调用curl命令,但每当我运行它总是给1作为答案是错误的。我的意思是我可以看到很多电话都有时间,但每次都给出1作为答案。我在做什么事吗?

for ((i=1;i<=1000000;i++)); do
curl --header "Authorization: Bearer some token here" "http://localhost:8080/v2/line?&clientid=120"
done \
| grep -wcoE '"errorCode":1001'

这是我在运行命令后看到的输出:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   226  100   226    0     0  12798      0 --:--:-- --:--:-- --:--:-- 17384
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   226  100   226    0     0   4591      0 --:--:-- --:--:-- --:--:--  7290
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   226  100   226    0     0   6318      0 --:--:-- --:--:-- --:--:--  8370
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   226  100   226    0     0   5252      0 --:--:-- --:--:-- --:--:--  7793
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   226  100   226    0     0   6139      0 --:--:-- --:--:-- --:--:--  8071
1

1 个答案:

答案 0 :(得分:2)

只需使用-s标志使卷曲保持沉默:

curl -s --header "Authorization: Bearer some token here" "http://localhost:8080/v2/line?&clientid=120"

或者将其错误输出重定向到/dev/null,如下所示:

curl -s --header "Authorization: Bearer some token here" "http://localhost:8080/v2/line?&clientid=120" 2>/dev/null

此外,您的计数版本将无法按预期工作。以下是您可以解决的问题:

timedout_count=0
for ((i=1;i<=1000000;i++)); do
    curl -s --header "Authorization: Bearer some token here" "http://localhost:8080/v2/line?&clientid=120" | 
        grep -q '"errorCode":1001' && timedout_count=$(( timedout_count + 1 ))
done 

echo "Timed out $timedout_count times"