Last active
November 16, 2023 08:26
-
-
Save pplmx/ce1108f25e194eb9ba309fd6e8d8c0cd to your computer and use it in GitHub Desktop.
define a retry_command function in Makefile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这段代码定义了一个名为
retry_command
的makefile
函数,它用于尝试执行一个命令直到成功,或者达到最大重试次数。这个函数接受三个参数:$(1)
: 要执行的命令。$(2)
: 最大重试次数,默认为10次。$(3)
: 每次重试之间的等待时间,默认为5秒。如果在达到最大重试次数后命令仍然失败,函数将输出一条错误消息并退出。
然后,这段代码定义了两个目标
x
和xx
,它们分别调用retry_command
函数来执行command -v jx
和x
命令。对于xx
目标,最大重试次数被设置为3次,每次重试之间的等待时间为1秒。这是一个非常实用的函数,可以用于处理网络不稳定或者其他原因导致的命令执行失败的情况。通过重试,可以增加命令成功执行的机会。