1

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.

4 Answers 4

5

use lsof for this task:

PORT=3030 kill $(lsof -t -ni:$PORT) 
4

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.

1

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)}' 
1

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.