如果 header 是 404,则写入文件,使用 Bash 并在 Linux 上卷曲

Write to file if header is a 404 using Bash and Curl on Linux

我有一个简单的脚本,它接受 2 个参数,一个 URL 和一个日志文件位置。理论上,它应该从 curl 命令捕获 header 状态代码,如果它是 404,则将 URL 附加到日志文件。知道它在哪里失败了吗?

#!/bin/bash
CMP='HTTP/1.1 404 Not Found'                                                        # This is the 404 Pattern
OPT=`curl --config /var/www/html/curl.cnf -s -D - ""  -o /dev/null | grep 404`    # Status Response
if [ $OPT = $CMP ] 
then
    echo "" >> ""                                                               # Append URL to File
fi

您的测试是将 $CMP 的值分配给 $OPT,而不是比较是否相等。尝试以下更简单的方法,它检查 grep 命令的 return 代码,而不是在其输出中查找比较字符串:

#!/bin/bash
CMP='HTTP/1.1 404 Not Found'
if $(curl -s -I "" | grep "$CMP" >/dev/null 2>&1); then
    echo "" >> ""
fi