2014-11-03 63 views
0

我正在努力解決linux bash中的問題。
我想一個腳本來執行命令檢查字符串是否在命令中答案

curl -s --head http://myurl/ | head -n 1 

,如果命令的結果包含了200則執行其他命令。 否則它是迴應的東西。 我現在擁有的一切:

CURLCHECK=curl -s --head http://myurl | head -n 1 
      if [[ $($CURLCHECK) =~ "200" ]] 
      then 
      echo "good" 
      else 
      echo "bad" 
      fi 

腳本打印:

HTTP/1.1 200 OK 
bad 

我嘗試過很多辦法,但他們都不似乎工作。 有人可以幫我嗎?

回答

1

我會這樣做:

if curl -s --head http://myurl | head -n 1 | grep "200" >/dev/null 2>&1; then 
    echo good 
else 
    echo bad 
fi 
+0

+1:請注意,'grep -q'由posix強制執行,因此應該被認爲是可移植的。 – 2014-11-03 20:28:03

+0

謝謝!它工作完美 – 2014-11-03 21:54:05

+0

'>&/ dev/null'簡稱。 – 2014-11-04 10:48:59

0

您可以使用此-w "%{http_code}" curl命令只得到HTTP狀態代碼:

[[ $(curl -s -w "%{http_code}" -A "Chrome" -L "http://myurl/" -o /dev/null) == 200 ]] && 
     echo "good" || echo "bad" 
+0

我仍然得到'bad'作爲輸出。但感謝您的快速反應! – 2014-11-03 20:25:12

+0

檢查我更新的答案以獲得更好的'curl'命令。 – anubhava 2014-11-03 20:42:12

0

你需要真正捕獲curl命令的輸出:

CURLCHECK=$(curl -s --head http://myurl | head -n 1) 

我很驚訝你'沒有找到「-s:command not found」錯誤

+0

謝謝,但即使當我這樣做。它仍然不起作用。 – 2014-11-03 21:57:05

0

使用wget

if wget -O /dev/null your_url 2>&1 | grep -F HTTP >/dev/null 2>&1 ;then echo good;else echo bad; fi