Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to kill a process in specified port (variable)

export PORT=3030
netstat -ntlp | awk '$4~/:*${PORT}$/{gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}'

but variable PORT doesn't get in the command.

share|improve this question
add comment

4 Answers

up vote 5 down vote accepted

use lsof for this task:

PORT=3030
kill $(lsof -t -ni:$PORT)
share|improve this answer
add comment

Try using double quotes to wrap the awk command instead of single quotes. Bash doesn't substitute variables inside single quotes.

You will need to either change the double quotes inside the command to single quotes or escape them with a backslash.

share|improve this answer
add comment

Adding to previous answers, just to show a way to fix your method:

netstat -ntlp | awk '$4 ~ PORT {gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}' PORT='3030'

or

export PORT=3030
netstat -ntlp | awk '$4~ ENVIRON["PORT"] {gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}'
share|improve this answer
add comment

The single quote ask the shell to pass the enclosed string without any change. So ${PORT} is not translated to 3030. It is only a bunch of characters as any other string.

Just use this: '$4~/:*'${PORT}'$/{gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}'
You close the single quote just before ${port} and reopen it just after (without any space). This will allow the shell to tranlate your variable.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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