2012-10-24 33 views
5

我正在嘗試使shell腳本讀取下載URL列表以查找它們是否仍處於活動狀態。我不確定我當前的腳本有什麼問題,(我是新手),任何指針都會有很大的幫助!使用Wget的Shell腳本 - 如果其他嵌套在循環中

用戶@ PC:〜/測試#貓sites.list

http://www.google.com/images/srpr/logo3w.png 
http://www.google.com/doesnt.exist 
notasite 

腳本:

#!/bin/bash 
for i in `cat sites.list` 
do 
wget --spider $i -b 
if grep --quiet "200 OK" wget-log; then 
echo $i >> ok.txt 
else 
echo $i >> notok.txt 
fi 
rm wget-log 
done 

不變,那麼腳本輸出一切notok.txt - (第一款谷歌網站應去ok.txt)。 但是,如果我運行:

wget --spider http://www.google.com/images/srpr/logo3w.png -b 

然後執行:

grep "200 OK" wget-log 

這裏grep沒有任何問題的字符串。我用語法做了什麼noob錯誤?感謝m8s!

回答

6

-b選項將wget發送到後臺,所以您在wget完成之前正在執行grep。

嘗試沒有-b選項:

if wget --spider $i 2>&1 | grep --quiet "200 OK" ; then 
+0

好趕! +1 – Graham

+0

確實。我也是+1。 :) – ghoti

+0

作品!謝謝! –

4

有你在做什麼的幾個問題。

  • 您的for i in會在包含空格的行中出現問題。最好使用while read來讀取文件的各個行。
  • 你沒有引用你的變量。如果文件中的一行(或一行中的單詞)以連字符開頭,會怎麼樣?那麼wget會將其解釋爲一個選項。這裏有潛在的安全風險,也有錯誤。
  • 創建和刪除文件並不是必須的。如果您所做的只是檢查URL是否可訪問,您可以在沒有臨時文件和額外代碼的情況下執行該操作。
  • wget不一定是最好的工具。我建議使用curl來代替。

所以這裏有一個更好的方式來處理這個問題......

#!/bin/bash 

sitelist="sites.list" 
curl="/usr/bin/curl" 

# Some errors, for good measure... 
if [[ ! -f "$sitelist" ]]; then 
    echo "ERROR: Sitelist is missing." >&2 
    exit 1 
elif [[ ! -s "$sitelist" ]]; then 
    echo "ERROR: Sitelist is empty." >&2 
    exit 1 
elif [[ ! -x "$curl" ]]; then 
    echo "ERROR: I can't work under these conditions." >&2 
    exit 1 
fi 

# Allow more advanced pattern matching (for case..esac below) 
shopt -s globstar 

while read url; do 

    # remove comments 
    url=${url%%#*} 

    # skip empty lines 
    if [[ -z "$url" ]]; then 
    continue 
    fi 

    # Handle just ftp, http and https. 
    # We could do full URL pattern matching, but meh. 
    case "$url" in 
    @(f|ht)tp?(s)://*) 
     # Get just the numeric HTTP response code 
     http_code=$($curl -sL -w '%{http_code}' "$url" -o /dev/null) 
     case "$http_code" in 
     200|226) 
      # You'll get a 226 in ${http_code} from a valid FTP URL. 
      # If all you really care about is that the response is in the 200's, 
      # you could match against "2??" instead. 
      echo "$url" >> ok.txt 
      ;; 
     *) 
      # You might want different handling for redirects (301/302). 
      echo "$url" >> notok.txt 
      ;; 
     esac 
     ;; 
    *) 
     # If we're here, we didn't get a URL we could read. 
     echo "WARNING: invalid url: $url" >&2 
     ;; 
    esac 

done < "$sitelist" 

這是未經測試。僅用於教育目的。可能含有堅果。

+1

+1美好的教學努力 –

+0

令人驚歎的是,這真的很有幫助!感謝ghoti。 –