-
-
Save pplmx/ce1108f25e194eb9ba309fd6e8d8c0cd to your computer and use it in GitHub Desktop.
# retry command with max retries and sleep time | |
# Notes: No Spaces between commas | |
# usage: $(call retry_command, command[,max_retries[,sleep_time]]) | |
# example1: $(call retry_command, command -v jx,3,1s) | |
# example2: $(call retry_command, command -v jx) | |
# example3: $(call retry_command, command -v jx,3) | |
define retry_command | |
@max_retries=$(or $(2),10); \ | |
sleep_time=$(or $(3),5s); \ | |
retries=0; \ | |
while ! $(1); do \ | |
retries=$$((retries + 1)); \ | |
if [[ $$retries -ge $$max_retries ]]; then \ | |
echo "Failed to execute command after $$max_retries attempts."; \ | |
exit 1; \ | |
fi; \ | |
echo "Retrying ($$retries/$$max_retries)..."; \ | |
sleep $$sleep_time; \ | |
done | |
endef | |
x: | |
$(call retry_command, command -v jx) | |
xx: | |
$(call retry_command, x,3,1s) |
pplmx
commented
Nov 16, 2023
This code defines a makefile
function named retry_command
that attempts to execute a command until it succeeds or reaches a maximum number of retries. This function takes three parameters:
$(1)
: The command to be executed.$(2)
: The maximum number of retries, defaulting to 10.$(3)
: The wait time between each retry, defaulting to 5 seconds.
If the command still fails after reaching the maximum number of retries, the function will output an error message and exit.
Then, this code defines two targets x
and xx
that call the retry_command
function to execute the command -v jx
and x
commands, respectively. For the xx
target, the maximum number of retries is set to 3 and the wait time between each retry is 1 second.
This is a very practical function that can handle situations where command execution fails due to unstable network or other reasons. By retrying, it increases the chance of successful command execution.
这段代码定义了一个名为 retry_command
的 makefile
函数,它用于尝试执行一个命令直到成功,或者达到最大重试次数。这个函数接受三个参数:
$(1)
: 要执行的命令。$(2)
: 最大重试次数,默认为10次。$(3)
: 每次重试之间的等待时间,默认为5秒。
如果在达到最大重试次数后命令仍然失败,函数将输出一条错误消息并退出。
然后,这段代码定义了两个目标 x
和 xx
,它们分别调用 retry_command
函数来执行 command -v jx
和 x
命令。对于 xx
目标,最大重试次数被设置为3次,每次重试之间的等待时间为1秒。
这是一个非常实用的函数,可以用于处理网络不稳定或者其他原因导致的命令执行失败的情况。通过重试,可以增加命令成功执行的机会。