Skip to content

Instantly share code, notes, and snippets.

@mohamedmansour
Created April 13, 2012 18:20
Show Gist options
  • Save mohamedmansour/2378922 to your computer and use it in GitHub Desktop.
Save mohamedmansour/2378922 to your computer and use it in GitHub Desktop.
Checks if a port is active, and if so, queries which server is running.
#!/bin/sh
# Mohamed Mansour (http://mohamedmansour.com)
if [ $# -ne 1 ]; then
echo "Usage: port_checker <port>"
exit 1
fi
PORT=$1
if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then
echo "Invalid argument: port must be a number.";
exit 1
fi
PID=$(netstat -tulpn | grep ":$PORT " | awk ' { split($7, array, "/") } END{ print array[1] } ')
if [ ! -n "$PID" ]; then
echo "No port is running on $PORT"
else
CWD=$(lsof -p $PID | awk '$4 == "cwd" { print $9 }')
TXT=$(lsof -p $PID | awk '$4 == "txt" { print $9 }')
echo "$TXT is running on port $PORT with pid $PID in $CWD"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment