如何使用bash shell脚本从文本文件中检查URL的状态

Jay*_* GK 11 linux url bash ubuntu http

我必须检查200个http URL的状态,并找出其中哪些是断开的链接.链接存在于一个简单的文本文件中(比如我的〜文件夹中的URL.txt).我正在使用Ubuntu 14.04,我是一个Linux新手.但我知道bash shell非常强大,可以帮助我实现我想要的.

我的确切要求是读取包含URL列表的文本文件,并自动检查链接是否正常工作,并将响应写入包含URL及其相应状态(工作/损坏)的新文件.

Jay*_* GK 19

我创建了一个文件"checkurls.sh"并将其放在我的主目录中,其中urls.txt文件也位于该目录中.我使用了给文件的执行权限

$chmod +x checkurls.sh

checkurls.sh的内容如下:

#!/bin/bash
while read url
do
    urlstatus=$(curl -o /dev/null --silent --head --write-out '%{http_code}' "$url" )
    echo "$url  $urlstatus" >> urlstatus.txt
done < $1
Run Code Online (Sandbox Code Playgroud)

最后,我使用以下命令从命令行执行 -

$./checkurls.sh urls.txt

瞧!有用.

  • 太棒了!如果您正在测试重定向,还可以使用`curl -H'Cache-Control:no-cache'-o / dev / null --silent --head --write打印目标URL并清除大多数301问题。 -out'%{http_code}%{redirect_url}'` (2认同)

kon*_*box 6

#!/bin/bash
while read -ru 4 LINE; do
    read -r REP < <(exec curl -IsS "$LINE" 2>&1)
    echo "$LINE: $REP"
done 4< "$1"
Run Code Online (Sandbox Code Playgroud)

用法:

bash script.sh urls-list.txt
Run Code Online (Sandbox Code Playgroud)

样品:

http://not-exist.com/abc.html
https://kernel.org/nothing.html
http://kernel.org/index.html
https://kernel.org/index.html
Run Code Online (Sandbox Code Playgroud)

输出:

http://not-exist.com/abc.html: curl: (6) Couldn't resolve host 'not-exist.com'
https://kernel.org/nothing.html: HTTP/1.1 404 Not Found
http://kernel.org/index.html: HTTP/1.1 301 Moved Permanently
https://kernel.org/index.html: HTTP/1.1 200 OK
Run Code Online (Sandbox Code Playgroud)

有关所有内容,请阅读Bash手册。见man curlhelpman bash以及。


bra*_*blc 5

如何为已接受的解决方案添加一些并行性。让我们修改脚本chkurl.sh以使其更易于阅读并且一次只处理一个请求:

#!/bin/bash
URL=${1?Pass URL as parameter!}
curl -o /dev/null --silent --head --write-out "$URL %{http_code} %{redirect_url}\n" "$URL"
Run Code Online (Sandbox Code Playgroud)

现在您可以使用以下方法检查您的列表:

cat URL.txt | xargs -P 4 -L1 ./chkurl.sh
Run Code Online (Sandbox Code Playgroud)

这可以将完成工作的速度提高 4 倍。