I'm writing a script that will spin up server that want to use certain port number. In some occasions this port is occupied. I want to know how to check it in bash so I can react in proper way.

How can I check on linux certain port is occupied?

2 Answers 2


You can use netcat to check if port is listening something:

PORT_STATUS=$(nc -v <host> -z <port number> 2>&1 | grep open | wc -l )
if [[ "$PORT_STATUS" = "1" ]];then
    echo Port is occupied

This of course only works if there isn't firewall blocking netcat. But if you run it locally on the server then at least there shouldn't be any problems.

  • I don't know is this because of flavor and/or version number but in my case nc gives me message "Connection to localhost 3306 port [tcp/mysql] succeeded!" so I suggest to use 'succeeded' instead of 'open' in grep. But except this everything is great!
    – sobi3ch
    May 23, 2016 at 18:59

If you have in mind TCP port, you can check with netstat, something like this might work:

 netstat -ntp |  grep -v '::' | awk  '{print $4}'  | grep -E '^[[:digit:]]+' | awk -F: '{print $2}' | sort -n | uniq

Of course this is not atomic, so it possible that some port will taken after check operation but before your service will start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.