【发布时间】:2014-03-07 12:22:05
【问题描述】:
我正在编写一个简单的 bash 脚本来“卷曲获取”一些值。有时代码有效,有时失败,并显示“来自服务器的空回复”。 如何在 bash 中对此进行检查,以便如果 curl 再次尝试失败,直到它获取值?
【问题讨论】:
-
在执行 curl 检查退出代码变量
$?并在需要时重试(不为零)。
我正在编写一个简单的 bash 脚本来“卷曲获取”一些值。有时代码有效,有时失败,并显示“来自服务器的空回复”。 如何在 bash 中对此进行检查,以便如果 curl 再次尝试失败,直到它获取值?
【问题讨论】:
$? 并在需要时重试(不为零)。
while ! curl ... # add your specific curl statement here
do
{ echo "Exit status of curl: $?"
echo "Retrying ..."
} 1>&2
# you may add a "sleep 10" or similar here to retry only after ten seconds
done
如果您希望该 curl 的输出在变量中,请随意捕获它:
output=$(
while ! curl ... # add your specific curl statement here
do
{ echo "Exit status of curl: $?"
echo "Retrying ..."
} 1>&2
# you may add a "sleep 10" or similar here to retry only after ten seconds
done
)
有关重试的消息会打印到 stderr,因此它们不会弄乱 curl 输出。
【讨论】:
人们过于复杂了:
until contents=$(curl "$url")
do
sleep 10
done
【讨论】:
对我来说,有时会在 curl 超时并且没有相关信息时发生。尝试使用 --connect-timeout 600(以秒为单位)卷曲,例如:
curl --connect-timeout 600 "https://api.morph.io/some_stuff/data.json"
也许这对你有帮助。
【讨论】:
如果您想尝试该命令直到成功,您可以说:
command_to_execute; until (( $? == 0 )); do command_to_execute; done
【讨论】: