01 / BUILD A TCP PORT SCANNER · LESSON 03

Run a complete scan plan

Collect every planned endpoint while preserving expected nonzero probe statuses.

22 min · learn at your pace

A failed probe is still a result

The plan and adapter now have separate responsibilities. The runner connects them: read one endpoint, invoke the adapter, record its result and continue. A refusal should not prevent later endpoints from being investigated. Neither should a missing observation silently disappear from the report.

Use a conditional to capture a command whose nonzero status is part of its contract. In an if assignment, the assignment has the command substitution's status. Save that status immediately in the else branch; another command would replace it. Prefixing the command with ! would invert its status, so it is unsuitable when you need the original number.

Avoid accidental subshell state

Redirect the plan into a grouped loop instead of piping cat into while. Pipeline components can run in subshells, which surprises scripts that expect counters or variables to survive after the loop. Here the rows go directly to a file, but establishing predictable loop scope helps as the tool grows.

Each input row has two validated nonempty fields. That promise makes tab-delimited read appropriate. Do not copy this parser unchanged to records with optional empty fields: whitespace IFS splitting can collapse them. Replace scan.tsv at the start of each completed run so an old observation cannot linger after the plan shrinks. These are recorded observations, not a claim of current reachability.

Try an example.sh
source lib/probe.sh
if state=$(probe 192.0.2.1 22);then status=0;else status=$?;fi
printf '%s (status %s)\n' "$state" "$status"
YOUR TURN

Put it into practice.

Source lib/probe.sh, which defines probe(address, port) with the previous lesson’s state/status contract. Read validated plan.tsv (address<TAB>port), preserving input order. Call probe once per row. Replace scan.tsv with address<TAB>port<TAB>state<TAB>status. Keep every row, including refused, timed_out, error and missing, and finish with script status 0. Repeated runs replace old rows. Do not modify plan.tsv or probes.tsv.

See an explained solution
One way to solve it.sh
source lib/probe.sh
printf 'address\tport\tstate\tstatus\n' > scan.tsv
{
 read -r header
 while IFS=$'\t' read -r address port;do
  if state=$(probe "$address" "$port");then status=0;else status=$?;fi
  printf '%s\t%s\t%s\t%s\n' "$address" "$port" "$state" "$status" >> scan.tsv
 done
} < plan.tsv

Expected probe failures are data rather than a reason to abandon the scan. The runner preserves both state and status, keeps endpoint order and replaces the report so previous observations cannot survive a smaller plan.