How to perform grep on curl within for loop?

跟風遠走 提交于 2020-07-03 17:40:11

问题


I have created an array uisng the command IFS=', ' read -r -a array <<< "$(command)"

The array has values:

abc001
abc002
abc003

I want to loop through the array and run a curl command on each element.

a) If curl output has string Connected then the curl command should timeout and the for loop should exit out.

b) If the curl output is not having string Connected then the curl command should timeout and for loop should move to next element.

I have written the following code.

for element in "${array[@]}"
do
 resp=$(curl -v http://"$element":8888)
 echo resp
done

I am getting following output:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* About to connect() to abc001 port 8888 (#0)
*   Trying 10.10.10.10...
* Connected to abc001 port 8888 (#0)

回答1:


Could you please try following, not tested though should work but.

for element in "${array[@]}"
do
 resp=$(curl -v http://"$element":8888)
 if grep -q "Connected" "$resp"
 then
      echo resp
 fi
done

OR

for element in "${array[@]}"
do
 curl http://"$element":8888 -s -f -o /dev/null
 if [[ $? -eq 0 ]]
 then
      echo "url $element is working."
 fi
done



回答2:


#!/bin/bash

for element in "${array[@]}"; do
  if curl -m1 -s "http://$element:8888"; then
    echo "'$element' connected" && break
  fi
done


来源:https://stackoverflow.com/questions/61764996/how-to-perform-grep-on-curl-within-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!