您的位置:首页 > 运维架构 > Shell

shell grep 查找进程的小技巧

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

[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/pptpd


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

[root@selboo ~]# ps aux | grep pptp | grep -v grep 
root 22054 0.0 0.1 1952 608 ? Ss Oct22 0:00 /usr/sbin/pptpd


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

[root@selboo ~]# ps aux | grep [p]ptp 
root 22054 0.0 0.1 1952 608 ? Ss Oct22 0:00 /usr/sbin/pptpd


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

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

使用grep -v grep 方式
[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.795s


使用正则方式
[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.784s
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: