brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: bash can test a TCP port through /dev/tcp without netcat

Bash
~/tips/tip-shell-dev-tcp-port-check

timeout 3 bash -c '</dev/tcp/192.168.1.x/443' && echo open || echo closed

Checks whether a TCP port accepts connections using only bash, no nc needed.

On a bare server or a slim container image there is often no nc or telnet, but there is bash. It can open sockets by itself, and I think that is a neat trick.

The manual describes it for redirections: with /dev/tcp/host/port, bash attempts to open the corresponding TCP socket, where host is a hostname or Internet address and port is a number or service name. If the open fails, so does the redirection. That gives you a port check with an exit code:

timeout 3 bash -c '</dev/tcp/192.168.1.x/443' && echo open || echo closed

If the connection is refused, bash prints Connection refused and the command fails, so you get closed. On bash 5.2 a port nobody listens on gives exactly that message. The timeout matters because a firewall that silently drops packets would otherwise leave you waiting for a long time.

The same works for a name, and the exit code is easy to use in a loop that waits for a service:

until timeout 2 bash -c '</dev/tcp/example.com/443'; do
  echo "waiting for example.com:443"
  sleep 5
done

Two caveats. This is a feature of bash, not a real device file, so cat /dev/tcp/... from another program or ls /dev/tcp finds nothing. And some builds of bash leave the feature out, in which case you get “No such file or directory”. A successful connect also proves only that something accepted the connection, not that the service behind it works.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link