5

ダウンロード URL のリストを読み取って、まだアクティブかどうかを確認するシェル スクリプトを作成しようとしています。現在のスクリプトの何が問題なのかわかりません (私はこれが初めてです)。ポインタがあれば非常に役立ちます!

user@pc:~/test# cat 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 に出力します (最初の Google サイトは ok.t​​xt に移動する必要があります)。しかし、私が実行した場合:

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

そして、次のようにします。

grep "200 OK" wget-log

問題なく文字列をgrepします。構文でどのような間違いを犯しましたか? ありがとうm8s!

4

2 に答える 2

6

-bオプションはwgetをバックグラウンドに送信しているため、wgetが終了する前にgrepを実行しています。

-bオプションなしで試してください。

if wget --spider $i 2>&1 | grep --quiet "200 OK" ; then
于 2012-10-24T02:47:52.070 に答える
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"

これはテストされていません。教育目的のみ。ナッツが含まれている可能性があります。

于 2012-10-24T03:03:16.107 に答える