AzLearn

تمرين إعادة البناء

Retry Wrapper

أعد كتابة wrapper في Bash يعيد محاولة أمر عند الفشل حتى حد معين.

bash ~14 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
#!/usr/bin/env bash
# Retry a command up to MAX_ATTEMPTS times with a delay between attempts.
# Note: we use `cmd` (not `command`) to avoid shadowing the `command` builtin.
set -euo pipefail

max_attempts="${MAX_ATTEMPTS:-3}"
delay_seconds="${DELAY_SECONDS:-1}"

if (($# > 0)); then
	cmd=("$@")
else
	cmd=(printf 'demo command succeeded\n')
fi

attempt=1

until "${cmd[@]}"; do
	if ((attempt >= max_attempts)); then
		printf 'Failed after %d attempts.\n' "$attempt" >&2
		exit 1
	fi

	printf 'Attempt %d failed, retrying in %ss...\n' "$attempt" "$delay_seconds" >&2
	sleep "$delay_seconds"
	((attempt++))
done

printf 'Succeeded on attempt %d.\n' "$attempt"
اكتب هنا