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