2012-10-24 16 views
5

ダウンロードURLのリストを読み込んで、まだアクティブであるかどうかを調べるシェルスクリプトを作成しようとしています。私は現在のスクリプトに何が問題なのかよく分かりません。(これは初めてです)、どんなポインタでも大きな助けになるでしょう!Wgetを使用したシェルスクリプト - ループ内でネストされている場合

ユーザー@パソコン:〜/テスト#猫のsites.list

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

スクリプト: - (最初のGoogleサイトすべき

#!/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に到達できるかどうかをチェックするだけであれば、一時ファイルと追加コードを削除して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。 –

関連する問題