最新消息:

shell grep 查找进程的小技巧

Shell admin 3浏览

大部分人在写Shell 过滤进程的时候 都会使用 grep 在 ps aux 的输出结果中查找指定的进程,但此时也会把 grep 进程也显示出来 比如查找 pptpd 进程,会匹配出来两条:

This is The Code

[root@selboo ~]# ps aux | grep pptp
root 20191 0.0 0.2 5108 704 pts/2 R+ 16:58 0:00 grep pptp
root 22054 0.0 0.1 1952 608 ? Ss Oct22 0:00 /usr/sbin/pptpdParsed in 0.000 seconds at N/A

常见的防止grep进程出现的方法就是在对加一个管道 grep -v grep 进行过滤:

This is The Code

[root@selboo ~]# ps aux | grep pptp | grep -v grep
root 22054 0.0 0.1 1952 608 ? Ss Oct22 0:00 /usr/sbin/pptpdParsed in 0.000 seconds at N/A

还有一个更方便的方法是用 正则 grep [p]ptpd来搜索pptpd这个进程:

This is The Code

[root@selboo ~]# ps aux | grep [p]ptp
root 22054 0.0 0.1 1952 608 ? Ss Oct22 0:00 /usr/sbin/pptpdParsed in 0.000 seconds at N/A

虽然说它比 grep -v grep 也未必方便多少,但是如果用大量循环的监控脚本上,每次都能减少一次系统grep调用,也就是减少一次创建进程,虽然提升很小可以忽略不计,但是用在shell写的监控脚本上来说多少还有点提升的,优化就是注重细节嘛。

以下是执行五次测试结果:

使用grep -v grep 方式

This is The Code

[root@selboo etc]# time for (( i=1; i<=200; i++ )) ;do ps aux | grep pptp | grep -v pptp &>/dev/null; done
real 0m1.487s 0m1.475s 0m1.488s 0m1.497s 0m1.499s
user 0m0.335s 0m0.328s 0m0.334s 0m0.326s 0m0.312s
sys 0m0.766s 0m0.757s 0m0.772s 0m0.784s 0m0.795sParsed in 0.000 seconds at N/A

使用正则方式

This is The Code

[root@selboo etc]# time for (( i=1; i<=200; i++ )) ;do ps aux | grep [p]ptp &>/dev/null; done
real 0m1.306s 0m1.344s 0m1.303s 0m1.298s 0m1.329s
user 0m0.343s 0m0.313s 0m0.326s 0m0.274s 0m0.322s
sys 0m0.742s 0m0.801s 0m0.753s 0m0.798s 0m0.784sParsed in 0.000 seconds at N/A

相关日志Linux ar 命令
Git 远程仓库的使用
mount disk Image
Could not open device at /dev/ipmi0

最后编辑: selboo 编辑于2012/12/29 17:48

转载请注明:爱开源 » shell grep 查找进程的小技巧