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

A data migration script runs for 40 minutes over 5,000 items. When it fails at item 3,000, rerunning starts from scratch. How do you make it resumable?

AdvancedScenarioScenarios: writing and hardening scripts
Answer

Situation read → Long batch jobs need checkpoints and idempotent steps, otherwise every failure costs the full runtime and may duplicate work.

What I'd do →

  1. Make each item idempotent (check before acting, or use upserts).
  2. Record progress in a state file after each item succeeds, written atomically:
    state=/var/lib/migrate/done.txt
    touch "$state"
    while IFS= read -r id; do
      grep -qxF -- "$id" "$state" && continue
      migrate_item "$id"
      printf '%s\n' "$id" >> "$state"
    done < items.txt
    
  3. For large sets, use a sorted done-list and comm -23 <(sort items.txt) <(sort "$state") to compute the remaining work once, instead of grepping per item.
  4. Take a lock so two resumptions cannot run at once, and add a --reset flag to clear state deliberately.
  5. Log a progress line every N items with an ETA.

Why → Checkpointing turns a 40-minute retry into a 1-minute one, and idempotency makes reruns safe.

Interview tip → Say you append to the state file only after the item succeeds, so a crash mid-item retries that item.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts