Timeout Wrapper Command Execution
Bound external commands with the timeout utility, distinguishing exit code 124 from genuine failures and retrying on it.
Code
#!/usr/bin/env bash
set -euo pipefail
readonly TIMEOUT_SECS=30
readonly MAX_RETRIES=2
run_with_timeout() {
local label="$1"
shift
local attempt=1
while (( attempt <= MAX_RETRIES + 1 )); do
timeout --kill-after=5s "${TIMEOUT_SECS}s" "$@" </dev/null
local code=$?
case "${code}" in
0)
echo "${label}: 成功"
return 0
;;
124)
echo "Error: ${label} 第 ${attempt} 次超时(${TIMEOUT_SECS}s)" >&2
(( attempt++ )) || true
;;
137)
echo "Error: ${label} 被强杀(TERM 后 5s 未退出)" >&2
return 137
;;
*)
echo "Error: ${label} 失败,退出码 ${code}" >&2
return "${code}"
;;
esac
done
echo "Error: ${label} 超时重试耗尽" >&2
return 124
}
# 用法:超时会重试,其他失败立即上抛
run_with_timeout "数据库迁移" ./migrate.sh --dry-run
run_with_timeout "健康探测" curl -sf http://127.0.0.1:8080/healthz
Inside the snippet
Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.
The work is delegated to readonly, timeout and run_with_timeout, chained through 2 pipes so each stage’s output feeds the next.
A helper function (run_with_timeout) keeps the repeated logic out of the main flow.
The key statements, annotated
while (( attempt <= MAX_RETRIES + 1 )); do
timeout --kill-after=5s "${TIMEOUT_SECS}s" "$@" </dev/null
(( attempt++ )) || true
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `readonly`, `timeout`, `run_with_timeout` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.