Checks whether a TCP host:port is reachable within a timeout, using only bash builtins (no netcat required). Use it before a deploy or in a health-check script.
#!/usr/bin/env bash
# Check TCP reachability of host:port within a timeout.
# Usage: port-check.sh <host> <port> [timeout_seconds]
set -euo pipefail
host="$1"
port="$2"
timeout_s="${3:-3}"
if timeout "$timeout_s" bash -c 'exec 3<>"/dev/tcp/$1/$2"' _ "$host" "$port" 2>/dev/null; then
echo "open"
else
echo "closed"
exit 1
fi
| host | string — positional argument, hostname or IP, e.g. db.internal |
|---|---|
| port | integer — positional argument, TCP port, e.g. 5432 |
| timeout_s | integer — optional 3rd argument, seconds to wait; defaults to 3 |
open and exits 0 if the connection succeeds within the timeout; prints
closed and exits 1 otherwise.
$ ./port-check.sh db.internal 5432
open
$ ./port-check.sh db.internal 9999 2
closed
host/port are passed into the inner bash -c as positional parameters ($1/$2), never string-interpolated into the command text, so a crafted hostname can't inject shell commands.set -euo pipefail ensures a missing argument fails loudly instead of running with an empty value.timeout so it can never hang a calling script indefinitely.