$_ CLI In Depth
Learning progress 0%
Build · Networking Tools

Build: A Port Health Checker

Write a checker for one port first, then extend it to many ports with a usage message and the right exit statuses.

~30 min Advanced 2 checked steps

Build it on a real Linux machine

The guided lab boots Linux in your browser. Each step runs a check script on that machine, so it passes only when your files and output are right.

What you will build

Step 1: Check one port

Create portcheck.sh in /workspace. It takes one port number as its argument. It tries to connect to 127.0.0.1 on that port within one second, prints the port and open when the connection works and the port and closed when it does not, and exits 0 for open and 1 for closed:

BASH10 lines
cat > portcheck.sh <<'EOF'
#!/usr/bin/env bash
port=$1
if timeout 1 bash -c "exec 3<>/dev/tcp/127.0.0.1/$port" 2>/dev/null; then
  echo "$port open"
  exit 0
fi
echo "$port closed"
exit 1
EOF

Step 2: Check many ports with usage

Replace portcheck.sh with a version that accepts any number of ports. For each port, print a line with the port and open or closed, and keep going after a closed port. Exit 1 if any port is closed, and exit 2 with a usage message on standard error when no arguments are given. Use a loop over the arguments and a status variable:

BASH17 lines
#!/usr/bin/env bash
# Usage: portcheck.sh PORT...
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"

Files

  • walkthrough.sh: every step of the reference solution, in order.

How it is checked

Each step in the guided lab has a check script that runs on the lab machine after you finish. It passes only when the files and output it expects are there, so the lab cannot be completed by reading alone.

Reference files

Read these after you have tried the lab. They are the solutions the checks were verified against.

walkthrough.sh

BASH35 lines
#!/usr/bin/env bash
# Reference solution for every step of the guided lab, in order.

# Step 1: Check one port
cat > /workspace/portcheck.sh <<&#039;EOF&#039;
#!/usr/bin/env bash
port=$1
if timeout 1 bash -c "exec 3<>/dev/tcp/127.0.0.1/$port" 2>/dev/null; then
  echo "$port open"
  exit 0
fi
echo "$port closed"
exit 1
EOF

# Step 2: Check many ports with usage
cat > /workspace/portcheck.sh <<&#039;EOF&#039;
#!/usr/bin/env bash
# Usage: portcheck.sh PORT...
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"
EOF

Lessons this build uses