如果你经常安装开发工具,肯定会使用 curl 命令行工具。它的选项极多,我想把它们一一梳理。本文从 -f 选项开始。
-f 和 --fail 选项的作用相同,用来处理下载出错的情况。
如果你访问一个 HTTP 资源时出错,HTTP 服务器通常会返回一个报错信息的 HTML 页面,解释一下为什么错了。curl 默认会打印输出这个报错信息。
$ curl https://example.com/not-exist-foo-bar
<!doctype html>
<html>
... 此处省略一万字...
</html>
如果使用 -f, --fail 选项,访问资源出错时,curl 将直接失败退出,不再继续下载或显示内容。
$ curl -f https://example.com/not-exist-foo-bar
curl: (56) The requested URL returned error: 404
$ echo $? # 查看报错退出码
56
-f, --fail 选项通常用于脚本的自动下载,通过检测 curl 退出码是否为 0,就能判断刚刚的下载是否成功。如果成功,可继续进行下一步。否则,需要处理下载错误的场景。
比如,我可以编写一个这样的 Shell 脚本文件,文件名是 download.sh:
curl -f https://example.com/not-exist-foo-bar
if [ $? -ne 0 ]; then
echo "请求失败"
fi
然后,给 download.sh 添加可执行权限,并运行它:
$ chmod a+x download.sh
$ ./download.sh
curl: (56) The requested URL returned error: 404
请求失败
如果你不想显示 curl 的错误信息(即上面的 curl: (56) The ... 这一行文字),可以使用 -s, --silent 选项,它会让 curl 闭嘴,进入静音模式。
简单修改一下 download.sh 文件:
curl -fs https://example.com/not-exist-foo-bar
if [ $? -ne 0 ]; then
echo "请求失败"
fi
继续运行这个脚本:
$ ./download.sh
请求失败
完