Tue 12 Jun 2007
Find Process ID by Port Number
Posted by admin under bash , linux , process , programming , shell[4] Comments
In linux you can use some shell scripting to find a running server process by port number. I came up with this example using awk (watch out for backticks `):
ps aux | grep --regexp="`netstat -nlept | awk '/:8079 / || /:8080 / {split($9,t,"/"); print t[1]}'`"
where you suspect the server ports to be 8079 or 8080. Problem here – if nothing is found then all processes will be listed. For automation you might prefer:
ps u --no-heading -p `netstat -nlept | awk '/[:]8080 / {split($9,t,"/"); print t[1]}'` 2>/dev/null
… last part will redirect error/help message in case there is no process.
Or put it into a function:
myserver_info() { ps aux | grep --regexp="`netstat -nlept | awk '/8079/ || /8080/ {split($9,t,"/"); print t[1]}'`"; }
this definition you can add to your .bashrc .
Usage:
myserver_info
or pass it within a pipe to “kill <pid>” command for example.
You can extend it further by passing the ports as function arguments … (see Advanced Bash-Scripting Guide: Functions)
Do you know a shorter way to do the same?