I have a very simple Bash Script. The goal of this bash script is to take in a parameter of a port number, and kill all processes running on that port.

PID_NUMBER=$(netstat -a -n -b -o | grep $1 | sed -e "s/[[:space:]]\+/ /g" | cut -d ' ' -f5)
echo "$PID_NUMBER"
taskkill /F /PID "$PID_NUMBER"

However, running the bash script in Cygwin echoes the PID_NUMBER, correctly, but throws an "ERROR: Invalid query" for taskkill


$ ./KillProcessesAtPort.sh 546
ERROR: Invalid query

If I run "taskkill /F /PID 1540" in Cygwin, the process is sucessfully terminated.

$ taskkill /F /PID 1540
SUCCESS: The process with PID 1540 has been terminated.

I am running this script in Windows 10 on Cygwin terminal. Why does my script throw an ERROR for taskkill whereas just executing taskkill in Cygwin works?

  • Have you tried taskkill /F /PID $PID_NUMBER with no quotes? – DavidPostill Aug 7 '17 at 19:57
  • Are you sure you did not edit the output of echo "$PID_NUMBER"? I encounter problems when the line is repeated more than once. – simlev Aug 9 '17 at 17:04

Here's what worked for me:

PID_NUMBER=$(netstat -a -n -b -o | grep $1 | sed -e "s/[[:space:]]\+/ /g" | cut -d ' ' -f6 | head -1)
echo "$PID_NUMBER"
taskkill /F /PID "$PID_NUMBER"

Note1: I had to replace -f5 with -f6 because otherwise I'd get a different column.
Note2: taskkill would fail with ERROR: Invalid query when more than one pid was returned. Solved by adding | head -1.

Conclusion1: Be aware that your solution is not robust: since netstat can output e.g. LISTENING before the pid you cannot reliably split the way you did.
Conclusion2: You should always pass a single value to taskkill, not a multiline string.

Suggestion: Differentiate for UDP and TCP, since TCP connections have a STATUS column:

PID_NUMBER=$(netstat -a -n -o | grep :$1 | awk '/UDP/{a=$4} /TCP/{a=$5} END{print a}')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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