Reputation: 623
I am trying to check port availability and get a return value using shell script. Example: if port 8080 is free then return true, else return false. Can anyone help? I tried with netstat
.
Upvotes: 3
Views: 15428
Reputation: 7931
Assuming you are using netstat from net-tools, this is a working example:
function is_port_free {
netstat -ntpl | grep [0-9]:${1:-8080} -q ;
if [ $? -eq 1 ]
then
echo yes
else
echo no
fi
}
eg.
$ is_port_free 8080
yes
$ is_port_free 22
no
Upvotes: 4
Reputation: 1055
lsof
is your friend:
# lsof -i:8080 # free on my machine
# echo $?
1
# lsof -i:5353 # occupied
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
mDNSRespo 64 _mdnsresponder 8u IPv4 0x9853f646e2fecbb7 0t0 UDP *:mdns
mDNSRespo 64 _mdnsresponder 9u IPv6 0x9853f646e2fec9cf 0t0 UDP *:mdns
# echo $?
0
So in a script, you could use !
to negate the value to test for availability:
if ! lsof -i:8080
then
echo 8080 is free
else
echo 8080 is occupied
fi
Upvotes: 18
Reputation: 11738
How about something simple:
netstat -an|egrep '[0-9]:8080 .+LISTENING'
Upvotes: 1