簡體   English   中英

使用curl使用列表文件從網頁獲取http代碼

[英]Use curl to get http code from webpage, using list file

我正在努力編寫腳本,並且是shell腳本的新手。

我正在嘗試創建一個腳本,該腳本將從源文件在多個網站上運行curl。

    arr_values=()
#Getting list of domains/websites to check, into array. 
read -ra arr_values <<< $(head -n 999 web.csv)

for s in "${arr_values[@]}"; do
#Running curl on each websites from list.
  res=$(curl -s -o /dev/null -w "%{http_code}" $s)

if [ $res == "200" ]; then 
    echo "OK"; 
elif
    [ $res == "302" ]; then
    echo "OK";
else
    echo "Error";
fi
done

但是我在沒有if語句的情況下運行時得到代碼000。 如果我手動運行它,一切正常。 並得出200或302。

您可以在表達式周圍使用單括號,即[和],而不是[[和]]。 您也可以從要檢查的值中刪除星號,即"200"而不是*"200"*

假設CSV文件是這樣的:

www.yahoo.com
www.google.ca

即每行一個站點。 還要在文件上運行dos2unix ,以確保該文件每行末尾都沒有“ \\ r \\ n”字符。

然后,運行以下代碼:

#!/bin/bash

arr_values=()
#Getting list of domains/websites to check, into array.
read -ra arr_values <<< $(head -n 999 web.csv)

for s in "${arr_values[@]}"
do
    #Running curl on each websites from list.
    res=$(curl -s -o /dev/null -w "%{http_code}" $s)

    if [ $res == "200" ]
    then
        echo "OK $s $res";
    elif [ $res == "302" ]
    then
        echo "OK $s $res";
    else
        echo "Error $s $res";
    fi
done

並得到以下輸出:

./t.bash 
Error www.yahoo.com 301
OK www.google.ca 200

修改內容:

  • 如果使用'=='驗證條件
  • 修改了echo語句,使其更易於調試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM