我正在做以下事情:
#!/usr/bin/perl
use strict;
use warnings;
my $proc = `ps -ef|grep -c myscriptname`;
print $proc;
当我在脚本中运行它时,它会打印 2。
ps -ef|grep -c myscriptname
在命令行上只显示:1
为什么?
同样适用于 my $proc = qx/ps -ef|grep -c myscriptname/
更新
明确地说,我从 somerandomscript.pl
更新 2
按照 edorqui 的建议,我删除了 -c
获取:
12013 15777 15776 0 14:11 pts/6 00:00:00 sh -c ps -ef | grep myscriptname
12013 15779 15777 0 14:11 pts/6 00:00:00 grep myscriptname Argument "12013 15777 15776 0 14:11 pts/6 00:00:00 sh -c ps..." isn't numeric in numeric gt (>) at somerandomscript.pl line 8
从脚本内部
最佳答案
ps -ef
命令显示了 grep 本身。
要跳过此行为,请尝试对与 grep 本身不匹配的正则表达式条件进行 grepping:
ps -ef | grep myscript[n]ame
或任何类似的东西:
ps -ef | grep myscriptnam[e]
说明
如果你在后台运行一个sleep
命令:
$ sleep 100 &
[1] 9768
然后用ps -ef
寻找它:
$ ps -ef | grep sleep
me 9768 3673 0 14:00 pts/6 00:00:00 sleep 100
me 9771 3673 0 14:00 pts/6 00:00:00 grep --color=auto sleep
你得到两行:进程本身和寻找它的 grep
命令。为了避免它并只显示过程本身,我们可以:
$ ps -ef | grep -v grep | grep sleep
或者在代码中使用正则表达式,使得grep进程不匹配:
$ ps -ef | grep slee[p]
me 9768 3673 0 14:00 pts/6 00:00:00 sleep 100
因为行
me 9771 3673 0 14:00 pts/6 00:00:00 grep --color=auto sleep
在 grep slee[p]
中不匹配。
关于linux - perl grep 和 cli grep 之间的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18146050/