执行命令wmic导致/ PID的taskkill参数出现问题?

问题描述

在Cygwin bash脚本文件中,当运行“ taskkill / PID $ pid”失败时,出现以下响应:“ .ROR:无效的参数/选项-”,在执行命令wmic之后执行

我在bash shell的以下文件中有以下6行,即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

在Cygwin Shell窗口中执行文件“ killpid.sh”时,如下所示:

./killpid.sh

工作正常。输出如下:

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

但是当更改为这6行时(取消注释第4行,并将pid分配给第4行的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

此响应失败:

escontrolpid is 5804
id is 1716
'.ROR: Invalid argument/option - '
Type "TASKKILL /?" for usage.

注意:进程ID 1716是5804的父进程(我使用命令wmic获取父pid),并且echo pid的字母'p'被截断到echo的输出

为什么执行wmic命令会导致/ PID的taskkill参数出现问题?

进一步调试,检查$ pid的长度,我发现罪魁祸首是作为$ pid值一部分的多余字符。这是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

和以下是输出

escontrolpid is 5804
4
7
pid is 1716
'.ROR: Invalid argument/option - '
Type "TASKKILL /?" for usage.

罪魁祸首的$ pid值为7,应该为4。

我如何修剪多余的3个十六进制?

解决方法

最后,我想通了,这是多余的回车符。 当我将$ pid的输出传递到文件中时,它有多余的一行。这是运行cat命令查看文件内容时的文件内容:

Administrator@mywin /cygdrive/c/test
$ cat test.txt
1716 <- an extra space after 6
     <- an blank line here
     <- an blank line here

注意:1716之后有两个空行 因此解决方法是通过以下命令修剪多余的回车符: tr -d'\ r'