[英]Error when awk command's parameter is being used in pattern
I'm running these commands: 我正在运行以下命令:
ps -ef | awk -v piddd="$child_pid" '$2 ~ /\<piddd\>/ { print $3; }'
ps -ef | awk -v piddd="$child_pid" '$2 ~ /piddd/ { print $3; }'
It doesn't give me any result. 它没有给我任何结果。 When I try with this one, I get what I need, although in some cases I'll get additional pids: 当我尝试使用此工具时,我会得到所需的东西,尽管在某些情况下,我还会得到其他pid
ps -ef | awk -v piddd="$child_pid" '$2 ~ piddd { print $3; }'
What is wrong with first ones? 第一个怎么了?
You cannot use a variable with the /pattern/
syntax. 您不能使用带有/pattern/
语法的变量。
If you want to add word boundaries (and your version of awk supports the syntax), you can do so by concatenating strings: 如果要添加单词边界(并且您的awk版本支持语法),则可以通过串联字符串来实现:
ps -ef | awk -v piddd="$child_pid" '$2 ~ "\\<" piddd "\\>" { print $3 }'
Note that the \\
must be escaped in this case. 请注意,在这种情况下, \\
必须转义。
If you just want the whole field to match the exact variable, I'd suggest using a simple string comparison: 如果您只想让整个字段匹配确切的变量,我建议使用简单的字符串比较:
ps -ef | awk -v piddd="$child_pid" '$2 == piddd { print $3 }'
There isn't a need to parse the output of ps
utility just to get the parent pid PPID
of a child PID
. 无需解析ps
实用程序的输出,而只是获取子PID
的父pid PPID
。 The ps
utility already provides this functionality. ps
实用程序已经提供了此功能。
ps -o ppid= -p $child_pid
The parameter -o ppid=
tells ps
to just print the parent pid. 参数-o ppid=
告诉ps
只打印父pid。 Without =
the printout will contain a header PPID
. 不=
打印输出将包含标题PPID
。
The parameter -p $child_pid
tells ps
to get the process information from the process id identified by variable $child_pid
. 参数-p $child_pid
告诉ps
从变量$child_pid
标识的进程ID中获取进程信息。
ps -ef | awk '$2 ~ /'`echo "$child_pid"`'/ { print $3; }'
# or
ps -ef | awk '$2 ~ /'$child_pid'/ { print $3; }'
# or create function
function father_pid() { ps -ef | awk '$2 ~ /'$1'/ { print $3; }'; }
# use function
father_pid $child_pid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.