linux - 如何使用curl检查文件是否下载

标签 linux bash shell curl

我正在写一个 shell 脚本,我需要从互联网上下载 6 个文件,在脚本中我已经这样做了

curl a
curl b
curl c
and so on

它可以工作,但有时 curl: (7) couldn't connect to host for some files in the middle of script,例如,它将成功下载 a 但错过文件 b错误,将下载文件 c。我想捕获此错误,以便我的代码在成功下载所有文件后执行。

最佳答案

你可以使用一个循环:

while true; do
  curl --fail b && break
done

在下载 b 之前,循环不会中断。您可以将其设置为重试函数,如果第一次尝试下载失败,您可以调用该函数:

retry(){
    while true; do
      curl --fail "$1" && break ||
      echo "Download failed for url: $1
            retrying..."
    done
}

然后这样做:

curl --fail a || retry a
curl --fail b || retry b
curl --fail c || retry c

如果你只想让错误消息静音,那么:

curl a 2>/dev/null
curl b 2>/dev/null
...

或者,如果您只想检测错误,则:

if ! curl --fail a; then
  echo "Failed"
fi

或者,一个衬垫:

curl --fail a || echo Failed

如果您想在失败后退出并显示您自己的消息:

curl --fail a 2>/dev/null || { echo failed; exit 1; }

关于linux - 如何使用curl检查文件是否下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37502839/

相关文章:

r - Ubuntu 22.04 中 R impish repo 的问题 - impish-cran40

linux - 在输出之前打印刚刚启动的进程的 pid

bash - 如何在 bash 中动态比较 awk 中的变量?

bash - 在 Bash 中将日期时间字符串转换为纪元

linux - For 循环不在 Shell 中的函数声明内运行

linux - 在 bash 中遍历数组时获取变量名

c - GList(glib-doubly-linked-list)线程安全吗?

linux - bash:如何传递包含空格的参数

linux - 格式化文本 Awk Sed

shell - grep 在目录中,并为 Unix Shell 脚本中的每个文件仅返回 1 个结果