验证 URL 是否存在

rmf*_*rmf 3 scripting wget curl

我想在不下载的情况下验证 URL 是否存在。我在下面使用curl

if [[ $(curl ftp://ftp.somewhere.com/bigfile.gz) ]] 2>/dev/null;
 then
  echo "This page exists."
 else
  echo "This page does not exist."
fi
Run Code Online (Sandbox Code Playgroud)

或使用wget

if [[ $(wget ftp://ftp.somewhere.com/bigfile.gz) -O-]] 2>/dev/null;
 then
  echo "This page exists."
 else
  echo "This page does not exist."
fi
Run Code Online (Sandbox Code Playgroud)

如果 URL 不存在,这很有效。如果存在,它会下载文件。就我而言,文件非常大,我不想下载。我只想知道那个 URL 是否存在。

dar*_*nir 6

你很接近。解决这个问题的正确方法是使用HEAD方法。

使用卷曲:

if curl --head --silent --fail ftp://ftp.somewhere.com/bigfile.gz 2> /dev/null;
 then
  echo "This page exists."
 else
  echo "This page does not exist."
fi
Run Code Online (Sandbox Code Playgroud)

或使用 wget:

if wget -q --method=HEAD ftp://ftp.somewhere.com/bigfile.gz;
 then
  echo "This page exists."
 else
  echo "This page does not exist."
fi
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,您可以使用“--spider”选项。 (2认同)

小智 5

我认为,最好将--spider论证与wget工具一起使用。它也适用于该wget工具的轻量级版本(在 BusyBox 中)。

例子:

URL="http://www.google.com"

if wget --spider "${URL}" 2>/dev/null; then
    echo "OK !"
else
    echo "ERROR ! Online URL ${URL} not found !"
fi
Run Code Online (Sandbox Code Playgroud)