Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 5 down vote accepted

use lsof for this task:

kill $(lsof -t -ni:$PORT)
share|improve this answer

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

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'


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

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

Your Answer


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.