TCP/IP Access Using bash

When executing a command on a /dev/tcp/$host/$port pseudo-device file, Bash opens a TCP connection to the associated socket.

A socket is a communications node associated with a specific I/O port. (This is analogous to a hardware socket, or receptacle, for a connecting cable.) It permits data transfer between hardware devices on the same machine, between machines on the same network, between machines across different networks, and, of course, between machines at different locations on the Internet.

The following examples assume an active Internet connection.

Getting the time from

bash$ cat

Generalizing the above into a script:

# This script must run with root permissions.


Downloading a URL:

bash$ exec 5<>/dev/tcp/
bash$ echo -e "GET / HTTP/1.0\n" >&5
bash$ cat <&5

Example 29-1. Using /dev/tcp for troubleshooting

# /dev/tcp redirection to check Internet connection.

# Script by Troy Engel.
# Used with permission. # A known spam-friendly ISP.
TCP_PORT=80 # Port 80 is http.

# Try to connect. (Somewhat similar to a 'ping' . . .)
echo "HEAD / HTTP/1.0" >/dev/tcp/${TCP_HOST}/${TCP_PORT}

: <From the bash reference:
If host is a valid hostname or Internet address, and port is an integer
port number or service name, Bash attempts to open a TCP connection to the
corresponding socket.

if [ "X$MYEXIT" = "X0" ]; then
echo "Connection successful. Exit code: $MYEXIT"
echo "Connection unsuccessful. Exit code: $MYEXIT"

exit $MYEXIT