The specification
The script is named portcheck.sh and takes one or more port numbers as arguments. For each port, it tries to connect to 127.0.0.1 on that port and waits at most one second. It prints a line with the port number and the word open or closed. It exits with status 0 when every port is open and with status 1 when any port is closed. A missing argument prints a usage message and exits with status 2.
Design decisions
The connection test uses the /dev/tcp path, which needs no extra program and works in bash. The timeout command limits the wait, because a connect to a filtered address can hang for a long time, and a probe that hangs is worse than one that fails. The result is recorded per port, so one script run reports every port instead of stopping at the first closed one.
The reference solution
The solution below follows the specification. Read it against the spec, one rule at a time.
#!/usr/bin/env bash
# Usage: portcheck.sh PORT...
# Prints "PORT open" or "PORT closed" for each port on 127.0.0.1.
set -u
if [ "$#" -eq 0 ]; then
echo "usage: portcheck.sh PORT..." >&2
exit 2
fi
status=0
for port in "$@"; do
if timeout 1 bash -c "exec 3<>/dev/tcp/127.0.0.1/$port" 2>/dev/null; then
echo "$port open"
else
echo "$port closed"
status=1
fi
done
exit "$status"The usage check comes first, so the loop never runs with no ports. The loop tests every argument and records a failure in status instead of exiting, which is what makes the script report all ports. The timeout command wraps a bash process that makes the connection, and its status is 0 only when the connection succeeds.
Why the test runs in a child bash
The timeout command runs its argument as a program, so the connection is made in a child bash. That child exits when the redirection finishes, which closes the descriptor. If the connection hangs, timeout kills the child and reports a failure, which the if statement treats as closed.
Testing the checker
Test the checker against a port that is open and one that is closed. To make a port open for a test, start a short-lived listener under timeout, as the raw TCP unit showed. The lab does exactly this, so the result does not depend on any service that happens to run on the machine.
Extensions to try
Add an option that reads ports from a file, one per line, or print the result as a single line for a log. Each change is small and reuses one of the patterns from this module. Test each one against an open port and a closed port.