Check Port Is Open in Shell Script

- - posted in ruby | Comments

nc is used to test for an open port, It returns 1 (non-zero) on failure and 0 (zero) on success.

Here are a couple of examples:

1
2
3
4
5
6
7
8
9
10
11
#!/bin/sh                                                                       

nc -z localhost 8983 < /dev/null

if [ $? == 0 ]; then
  bundle exec rake sunspot:solr:reindex
else
  echo ''
  echo 'Solr is not running, start Solr with "foreman start" and then run "rake sunspot:solr:reindex to update the index"'
  echo ''
fi
1
2
3
4
5
6
7
#!/bin/sh
echo "Restarting Unicorn on port 9000"
fuser -k 9000/tcp
while nc -vz localhost 9000; do sleep 1; done
bundle exec unicorn_rails -p 9000 -E production -D
while ! nc -vz localhost 9000; do sleep 1; done
curl http://localhost:9000

Comments