How to check whether a particular port is open on a machine from a shell script and perform action based on that?
The program lsof
allows you to check which processes are using which ressources, like files or ports.
To show which processes are listening on port 8080:
lsof -Pi :8080 -sTCP:LISTEN
In your case, you want to test whether a process is listening on 8080 - the return value of this command tells you just that. It also prints the pid of the process.
lsof -Pi :8080 -sTCP:LISTEN -t
If you need just the test, with no output, redirect it to /dev/null
:
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null ; then
echo "running"
else
echo "not running"
fi
If you use multiple host names with multiple IP addresses locally, specify the hostname too like
lsof -Pi @someLocalName:8080 -sTCP:LISTEN
Simplest way in bash. Test if your port is open.
(echo >/dev/tcp/localhost/8080) &>/dev/null && echo "TCP port 8080 open" || echo "TCP port 8080 not open"
Replace the port with what you are testing.
Or you can use nc.
nc -vz 127.0.0.1 8080
Returns:
Connection to 127.0.0.1 8080 port [tcp/*] succeeded
Elaborating on RJ's answer which notes nc
is also useful... Not only is nc
useful for quick command-line query
❯ nc -z -v -w5 127.0.0.1 8080
localhost [127.0.0.1] 8080 (http-alt) : Connection refused
but it can be used without -v if the human-readability thing isn't what you're after -- e.g., for use in a script (the exit code will indicate whether the port is open or closed).
❯ nc -z 127.0.0.1 8080
❯ echo $?
1