Write a function that retries a command up to N times with exponential backoff.

IntermediateHands-onBash scripting tasks
Answer
retry() {
  local max="$1"; shift
  local n=1 delay=2
  until "$@"; do
    if (( n >= max )); then
      echo "Command failed after $n attempts: $*" >&2
      return 1
    fi
    echo "Attempt $n failed, retrying in ${delay}s..." >&2
    sleep "$delay"
    n=$((n + 1)); delay=$((delay * 2))
  done
}

retry 5 curl -sf https://api.example.com/health

Key trick → "$@" passes the command and its arguments through intact, quoting included, so it works for any command.

All Real-World Interview questions Roadmap: Interview readiness

More on Bash scripting tasks