TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Logging, Retries and Timeouts in Bash

Logging, Retries and Timeouts in Bash

Scripts that run unattended talk to things that fail: package mirrors, APIs, databases that are still starting. They need to say clearly what they are doing, try again when a failure is likely to be temporary, and give up when something hangs. This lesson builds three small functions for that: log, retry and a timeout wrapper.

A log function with levels

Good script logs have a timestamp, a level and a message, go to stderr, and can be made quieter or louder without editing the script:

bash · try it yourself
cat > lib.sh <<'LIB'
# lib.sh: logging helpers, meant to be sourced
LOG_LEVEL=${LOG_LEVEL:-info}
declare -A _LOG_RANK=([debug]=10 [info]=20 [warn]=30 [error]=40)
log() {   # log LEVEL MESSAGE...
  local level=$1; shift
  [ "${_LOG_RANK[$level]}" -ge "${_LOG_RANK[$LOG_LEVEL]}" ] || return 0
  printf '%s %-5s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${level^^}" "$*" >&2
}
LIB
cat > sync.sh <<'SCRIPT'
set -euo pipefail
source ./lib.sh
log debug "reading config from ./sync.conf"
log info  "syncing 3 buckets"
log warn  "bucket logs-old is empty, skipping"
log error "bucket images: access denied"
SCRIPT
echo "== default level (info)"; bash sync.sh
echo "== LOG_LEVEL=warn";       LOG_LEVEL=warn bash sync.sh
echo "== stdout only";          bash sync.sh 2>/dev/null | wc -l
== default level (info)
2026-10-27T07:54:45Z INFO  syncing 3 buckets
2026-10-27T07:54:45Z WARN  bucket logs-old is empty, skipping
2026-10-27T07:54:45Z ERROR bucket images: access denied
== LOG_LEVEL=warn
2026-10-27T07:54:45Z WARN  bucket logs-old is empty, skipping
2026-10-27T07:54:45Z ERROR bucket images: access denied
== stdout only
0
  • UTC ISO 8601 timestamps (2026-01-15T10:00:00Z) sort correctly as text and mean the same thing on every server. The times in the output above are whatever the clock said when this page was generated.
  • The level comes from the environment, so a cron entry or CI job can set LOG_LEVEL=debug for one run.
  • Under systemd or in a container, stderr already goes to the journal or the container log, which add their own timestamps; there you may drop the date and keep only the level. When a log collector parses your output, consider one JSON object per line instead (jq in Scripts shows how to build JSON safely in Bash).
  • logger -t myscript "message" sends a line to syslog/journald directly, useful for cron jobs whose stderr would otherwise be mailed or lost.

retry with exponential backoff

A temporary failure (a 503, a connection refused while a service restarts, a lock held by another job) is often gone a moment later. Retrying immediately in a tight loop hammers the thing that is already struggling; waiting longer after each attempt (exponential backoff) gives it room. The flaky command below fails twice, then succeeds:

bash · try it yourself
cat > retry.sh <<'SCRIPT'
set -euo pipefail
retry() {   # retry MAX_ATTEMPTS COMMAND...
  local max=$1 attempt=1 delay=0.1; shift
  until "$@"; do
    local rc=$?
    if [ "$attempt" -ge "$max" ]; then
      echo "retry: giving up after $attempt attempts (last status $rc)" >&2
      return "$rc"
    fi
    echo "retry: attempt $attempt failed (status $rc), waiting ${delay}s" >&2
    sleep "$delay"
    attempt=$((attempt + 1))
    delay=$(awk -v d="$delay" 'BEGIN { print d * 2 }')
  done
}
flaky() {   # fails until it has been called $1 times
  local n; n=$(( $(cat calls 2>/dev/null || echo 0) + 1 )); echo "$n" > calls
  [ "$n" -ge "$1" ] && echo "flaky: success on call $n"
}
retry 5 flaky 3; echo "-> status $?"
rm -f calls
retry 2 flaky 3 || echo "-> status $?"
SCRIPT
bash retry.sh
retry: attempt 1 failed (status 1), waiting 0.1s
retry: attempt 2 failed (status 1), waiting 0.2s
flaky: success on call 3
-> status 0
retry: attempt 1 failed (status 1), waiting 0.1s
retry: giving up after 2 attempts (last status 1)
-> status 1

Points to keep in mind:

  • Only retry what is safe to repeat: a read, an idempotent PUT, a download. Retrying "create order" can create two orders.
  • Only retry temporary failures. A 404 or "permission denied" will fail the same way five times; production retry helpers check the status before retrying. Retries, Backoff and Pagination does this properly in Python, with jitter.
  • Cap the total time. Five attempts with doubling delays starting at 1 s already wait 1 + 2 + 4 + 8 = 15 s.
  • Many tools retry by themselves: curl --retry 5 --retry-delay 2 --retry-connrefused, apt-get -o Acquire::Retries=3, git has none (wrap it).
bash
# curl: retry transient errors, fail on HTTP errors, bound the whole call
curl --fail --silent --show-error \
     --retry 5 --retry-delay 2 --retry-connrefused --max-time 30 \
     -o release.tar.gz https://downloads.example.com/app/1.4.2/release.tar.gz

Timeouts: never wait forever

A hung command is worse than a failed one: the job holds its lock, the pipeline never finishes, and nobody is alerted. GNU timeout runs a command with a deadline and exits with 124 when the deadline hit:

bash · try it yourself
timeout 1 sleep 5; echo "sleep 5 with a 1s timeout: status $?"
timeout 5 sleep 0.1; echo "sleep 0.1 with a 5s timeout: status $?"
{ timeout -k 1 1 bash -c 'trap "" TERM; sleep 5'; } 2>/dev/null
echo "ignores TERM, killed after the grace period: status $?"
sleep 5 with a 1s timeout: status 124
sleep 0.1 with a 5s timeout: status 0
ignores TERM, killed after the grace period: status 137

timeout sends SIGTERM first; -k 1 adds a SIGKILL one second later for programs that ignore TERM (status 137 = 128 + 9). The 2>/dev/null around it only hides the shell's own "Killed" job report. Combine the two helpers so each attempt is bounded too: retry 3 timeout 10 ./healthcheck.

Test yourself

Why should script log messages go to stderr?

  1. stderr is faster
  2. So that stdout carries only the script's data and can be piped or captured safely
  3. systemd ignores stdout
  4. Because printf requires it

Which failure is a good candidate for an automatic retry?

  1. HTTP 404 Not Found
  2. Permission denied
  3. Connection refused while the service restarts
  4. A syntax error in the config file

What exit status does timeout 1 sleep 5 return?

  1. 0
  2. 1
  3. 124
  4. 143