When writing a Shell filter process, most people use grep to search for the specified process in the output result of ps aux. However, the grep process is also displayed, for example, the pptpd process, two matching items are displayed:
Copy codeThe Code is as follows: [root @ selboo ~] # Ps aux | grep pptp
Root 20191 0.0 0.2 5108 704 pts/2 R + grep pptp
Root 22054 0.0 0.1 1952 608? Ss Oct22 0: 00/usr/sbin/pptpd
A common method to prevent grep processes is to filter grep-v grep by adding a pipeline:
Copy codeThe Code is as follows: [root @ selboo ~] # Ps aux | grep pptp | grep-v grep
Root 22054 0.0 0.1 1952 608? Ss Oct22 0: 00/usr/sbin/pptpd
Another more convenient method is to use the regular grep [p] ptpd to search for the pptpd process:
Copy codeThe Code is as follows: [root @ selboo ~] # Ps aux | grep [p] ptp
Root 22054 0.0 0.1 1952 608? Ss Oct22 0: 00/usr/sbin/pptpd
Although it is not necessarily more convenient than grep-v grep, if a large number of Cyclic Monitoring scripts are used, the system grep call can be reduced every time, that is, the process creation can be reduced, although the improvement is negligible, there are still some improvements in the monitoring script written by shell. Optimization focuses on details.
The following are the results of the five tests:
Use grep-v grepCopy codeThe Code is as follows: [root @ selboo etc] # time for (I = 1; I <= 200; I ++ )); do ps aux | grep pptp | grep-v pptp &>/dev/null; done
Real 0m1. 487 s 0m1. 475 s 0m1. 488 s 0m1. 497 s 0m1. 499 s
User 0m0. 335 s 0m0. 328 s 0m0. 334 s 0m0. 326 s 0m0. 312 s
Sys 0m0. 766 s 0m0. 757 s 0m0. 772 s 0m0. 784 s 0m0. 795 s
Use Regular ExpressionCopy codeThe Code is as follows: [root @ selboo etc] # time for (I = 1; I <= 200; I ++ )); do ps aux | grep [p] ptp &>/dev/null; done
Real 0m1. 306 s 0m1. 344 s 0m1. 303 s 0m1. 298 s 0m1. 329 s
User 0m0. 343 s 0m0. 313 s 0m0. 326 s 0m0. 274 s 0m0. 322 s
Sys 0m0. 742 s 0m0. 801 s 0m0. 753 s 0m0. 798 s 0m0. 784 s