首页 > 解决方案 > 检查网页是否已更改的脚本

问题描述

我有一个任务,我必须从文本文件(sites.txt)中读取网站列表,并检查自上次运行脚本以来是否有任何静态更改。我的输入是

https://en.wikipedia.org/wiki/Stack_Overflow
https://en.wikipedia.org/wiki/Linux
https://en.wikipedia.org/wiki/Linus_Torvalds

如果任何网站出现故障,它应该将地址名称和消息 FAILED 打印到 stderr,就像这个输出示例一样。

https://en.wikipedia.org/wiki/Stack_Overflow FAILED

此外,如果输入文本文件包含 # 它应该忽略该行作为注释。我的尝试是创建 2 个 html 文件 old.html 和 new.html 并在 html 文件的减法不同于 0 时检查 if 语句。我的问题是我的输出与我预期的奇怪不同,并且 curl 命令始终假定网站已关闭。我的输出是:

 FAILED/en.wikipedia.org/wiki/Stack_Overflow
 FAILED/en.wikipedia.org/wiki/Linux
https://en.wikipedia.org/wiki/Linus_Torvalds FAILED

这是我的代码:

#!/bin/bash

while read line || [ -n "$line" ]; do
    [[ "$line" = "\#*" ]] && continue
    if [ "$(curl -s --head  --request GET "$line" | grep "200 OK" > /dev/null)" ]; then
        mv new.html old.html 2> /dev/null
        curl "$line" -L --compressed -s > new.html 
        DIFF_OUTPUT="$(diff new.html old.html)"
        if [ "0" != "${#DIFF_OUTPUT}" ]; then
            echo "$line Changed"
        fi  
    else
        echo "$line FAILED" >&2
    fi
done <"$1"

谁能帮我?

标签: linuxbashshell

解决方案


sites.txt具有 DOS 行结尾\r\n而不是 UNIX 行结尾\n\r回车使光标移回第一列。您需要转换sites.txt为 UNIX 格式$line.


推荐阅读