您现在的位置是:网站首页> 编程资料编程资料
shell grep 查找进程的小技巧_linux shell_
2023-05-26
287人已围观
简介 shell grep 查找进程的小技巧_linux shell_
大部分人在写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
复制代码 代码如下:
[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
相关内容
- Linux下Oracle归档日志自动清理脚本代码(sh)_linux shell_
- Linux Shell中判断进程是否存在的代码_linux shell_
- Linux命令行和shell脚本编程宝典 Richard Blum_linux shell_
- shell 字符串操作(长度,查找,替换)详解_linux shell_
- shell 中数学计算总结_linux shell_
- hbase shell基础和常用命令详解_linux shell_
- shell 基本计算、逻辑运算、位运算详解_linux shell_
- 关于Shell脚本效率优化的一些个人想法_linux shell_
- BASH 学习笔记小结_linux shell_
- bash 编程中循环语句用法_linux shell_
