我有一个使用 curl 的脚本来检查远程网站上是否存在该文件,但我刚刚意识到即使该文件不在远程服务器上,我也会收到状态代码 200。我想知道如何纠正这个问题?< /p>
我已经检查了一些以前的帖子,但还没有工作结果。
if [ -z "$found" ];then
echo "File does not exist....."
statuscode=`curl -Is --head --silent https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4 | head -1 | awk '{print $2}'`
statuscode=$(echo "$statuscode" | tr -d '\r')
echo "Status is : $statuscode"
if [ "$statuscode" == "200" ]
then
cd /var/www/html/led/autoplayv/ && wget https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4
sudo /run.sh
else
echo "Url Not Found or File not Found"
fi
答案 0 :(得分:0)
那里有很多不必要的复杂性。只需使用 curl --fail
,您就可以在其退出状态上进行分支以检测失败并事后清理:
#!/usr/bin/env bash
url=https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4
dest=/var/www/html/led/autoplayv/
if [ -z "$found" ]; then
curl --fail -o "${dest}/${url##*/}" "$url" || {
echo "ERROR: Unable to download $url" >&2
rm -f -- "${dest}/${url##*/}"
}
fi
这还可以防止 TOCTOU 问题(由于检查时间和使用时间之间的差异而导致代码失败的地方——例如,如果文件在第一次检查期间存在但在第二次检查发生之前被删除,与原代码轮询两次;而上面,我们只检查一次,所以检查时间和使用时间没有区别)。