首页 > 解决方案 > For循环监视未加载的站点

问题描述

我管理着大量的站点,并希望找到一种廉价的方法来让自己知道其中一个站点何时无法加载,以最大程度地减少客户发现他们的站点在我之前出现故障的次数。我决定创建一个 for 循环来加载域名并输出返回 200 响应以外的任何内容的域。谁能帮我语法?我不知道该怎么做。

到目前为止,我相信它是:for i in $; do curl -L $;

除了我上面的内容,我不确定如何获得对我每天都会检查域的文件的响应。

您能提供的任何东西都将不胜感激。

标签: bashfor-loopcurlpipe

解决方案


你可以定义这个 bash 函数:

httpstatus() {
    file=$1

    # read file line by line
    while IFS= read -r site; do

        # print sites that do not return status 20X or 30X
        if [[ $(curl -o /dev/null -sIw '%{http_code}\n' $site) != [23]0[0-2] ]]; then
            echo $site
        fi

    done < "$file"
}

示例用法:

$ cat sites
https://stackoverflow.com
https://example.com
https://example.com/returns-404
$ httpstatus sites
https://example.com/returns-404

Bash 语法和内置命令记录在man bash. BashFAQ是其他有用的资源。


推荐阅读