← all snippets

port-check

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.

Bash #06

Source

port-check.sh
#!/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

Input

hoststring — positional argument, hostname or IP, e.g. db.internal
portinteger — positional argument, TCP port, e.g. 5432
timeout_sinteger — optional 3rd argument, seconds to wait; defaults to 3

Output

Prints open and exits 0 if the connection succeeds within the timeout; prints closed and exits 1 otherwise.

Usage

$ ./port-check.sh db.internal 5432
open

$ ./port-check.sh db.internal 9999 2
closed

Config

No configuration required.

Security notes

  • 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.
  • Bounded by an explicit timeout so it can never hang a calling script indefinitely.