Interview Prep/Shell Scripting/Troubleshooting: strict mode, exit codes, pipelines and traps

Pressing Ctrl+C during `while read -r host; do ssh -n "$host" uptime; done < hosts.txt` only skips to the next host. You have to press it 40 times.

IntermediateTroubleshootingTroubleshooting: strict mode, exit codes, pipelines and traps
Answer

Likely causes → SIGINT goes to the foreground process group. ssh handles it and exits with its own status (255) rather than dying from the signal, so Bash concludes the child handled Ctrl+C and the loop simply continues.

Diagnose → Check $? after the interrupted ssh (255 or 130 instead of the shell itself exiting). trap -p INT shows no trap is set.

Fix → Trap INT and TERM in the script so it stops itself:

trap 'echo "interrupted" >&2; exit 130' INT
trap 'echo "terminated" >&2; exit 143' TERM
while read -r host; do
  ssh -n -o ConnectTimeout=5 "$host" uptime || echo "$host: failed ($?)" >&2
done &lt; hosts.txt

Prevent → Every long-running loop script gets INT/TERM traps that exit with 128+signal and let the EXIT trap clean up.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: strict mode, exit codes, pipelines and traps