In a Cygwin bash script file when run "taskkill /PID $pid" failed with this response: ".ROR: Invalid argument/option -" after the line execution of the command wmic.
I had the following 6 lines in bash shell in a file namely killpid.sh:
#!/bin/sh
escontrolpid=$(tasklist | grep CONTROL | awk '{ print $2 }')
echo "escontrolpid is $escontrolpid"
#escontrolparentpid=$(wmic process where processid=$escontrolpid get parentprocessid | grep -v -i parentprocessid)
pid=$escontrolpid
echo "pid is" $pid
taskkill /PID $pid
When execute the file "killpid.sh" in Cygwin shell window like so:
./killpid.sh
It worked fine. Here were the output:
escontrolpid is 5804
pid is 5804
ERROR: The process with PID 5804 could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).
But when change to these 6 lines (Uncomment the line # 4 and assign pid to the line 4's var):
escontrolpid=$(tasklist | grep CONTROL | awk '{ print $2 }')
echo "escontrolpid is $escontrolpid"
escontrolparentpid=$(wmic process where processid=$escontrolpid get parentprocessid | grep -v -i parentprocessid)
pid=$escontrolparentpid
echo "pid is" $pid
taskkill /PID $pid
It failed with this response:
escontrolpid is 5804
id is 1716
'.ROR: Invalid argument/option - '
Type "TASKKILL /?" for usage.
Note: process id of 1716 is the parent process of 5804 (i use command wmic to get the parent pid), and also the echo pid got the letter 'p' truncated to the output of the echo.
Why the execution of the command wmic causing issue for taskkill argument of /PID?
Further debugging, with inspect the length of the $pid, i found that the culprit is the extra characters as part of the value of $pid. Here was the modified script body of the killpid.sh:
escontrolpid=$(tasklist | grep CONTRO | awk '{ print $2 }')
echo escontrolpid is $escontrolpid
echo $escontrolpid > ./test.txt
sed 's/[^\x[0-9A-Fa-f][0-9A-Fa-f]]//g' ./test.txt | awk '{ print length }'
escontrolparentpid=$(wmic process where processid=$escontrolpid get
parentprocessid | grep -v -i parentprocessid | grep -v -e '^[[:space:]]*$')
pid=$escontrolparentpid
echo $pid > ./test.txt
sed 's/[^\x[0-9A-Fa-f][0-9A-Fa-f]]//g' ./test.txt | awk '{ print length }'
echo pid is $pid
taskkill /PID $pid
and the followings were the output:
escontrolpid is 5804
4
7
pid is 1716
'.ROR: Invalid argument/option - '
Type "TASKKILL /?" for usage.
The culprit $pid value is 7, and it should be 4.
How can i trim the extra 3 hex?