Assuming you are using netstat from network 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
}
- $ {1: -8080} means using the first argument as a port and 8080 if there is no first argument
- grep -q [0-9]: port means matching a number followed by a colon followed by a port
- $? - . , . 0 . grep 1 . -q , , .
- netstat -ltnp n umeric ports IP p rograms, l t cp.
- a | b a b
.
$ is_port_free 8080
yes
$ is_port_free 22
no