Interview Prep/Shell Scripting/Scenarios: writing and hardening scripts

A container entrypoint (Alpine, POSIX `sh` only) must wait for Postgres before running migrations. Write the approach.

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → No Bash, so no /dev/tcp, arrays or [[ ]]. The wait must be bounded, and the app must become PID 1.

What I'd do →

#!/bin/sh
set -eu
deadline=$(( $(date +%s) + ${DB_WAIT_SECONDS:-60} ))
until pg_isready -q -h "$DB_HOST" -p "${DB_PORT:-5432}"; do
  if [ "$(date +%s)" -ge "$deadline" ]; then
    echo "database not ready after ${DB_WAIT_SECONDS:-60}s" >&2
    exit 1
  fi
  sleep 2
done
./migrate up
exec "$@"
  1. pg_isready comes with the Postgres client package; nc -z host port is a fallback.
  2. exec "$@" hands PID 1 to the real process so it receives SIGTERM.
  3. Check with shellcheck -s sh entrypoint.sh.

Why → Unbounded waits hang deploys; a missing exec breaks graceful shutdown.

Interview tip → Mention that in Kubernetes, readiness probes and init containers are often a better place for this than the entrypoint.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts