Robert Meyer Robert Meyer - 2 years ago 112
Bash Question

Passing a port number to lsof in a shell function

I wrote an alias in my bash profile to help me kill rogue rails server processes that don't cleanly close. This alias works well.

alias kill3000="lsof -i tcp: 3000 -t | xargs kill -9 | echo 'killed processes on port 3000'"

I wanted to make it more general purpose, for frameworks that work on other ports. I tried to make a similar function, so I could pass the port number as a variable, but I get an error. The function I wrote looks like this...

function killproc (){
"lsof -i tcp:$1 -t | xargs kill -9 | echo 'killed processes on port $1'"

However, when I run "killproc 3000", I get the following error:

lsof: unacceptable port specification in: -i tcp:

I'm struggling to understand the problem, I appreciate any help.

Answer Source

Maybe the double-quotes are involved.

Give a try to this:

function killproc (){
    lsof -i tcp:"$1" -t | xargs kill -9
    lsof -i tcp:"$1" -t 2>/dev/null >/dev/null || printf "killed processes on port %s\n" "$1"

The message is printed only if there is no more process found listening on the port pspecified.

If you get some troubles, follow @shellter instruction. Run a test with set -vx ; killproc 300 ; set +vxand edit the question to add the output generated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download