grep 不显示自身的方法
使用 grep 的 -v 参数
- 未使用 -v 时的效果
$ ps -ef|grep hellcat-mess
dev 1099472 1 2 11:44 ? 00:05:21 ./hellcat-messenger
dev 1270113 1248460 0 15:40 pts/23 00:00:00 grep --color=auto hellcat-mess
- 使用 -v 时的效果
$ ps -ef|grep hellcat-mess|grep -v grep
dev 1099472 1 2 11:44 ? 00:05:21 ./hellcat-messenger
- 原理
-v, --invert-match 反向匹配
Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)
使用正则
- 示例
$ ps -ef|grep hellcat-mes[s]
dev 1099472 1 2 11:44 ? 00:05:25 ./hellcat-messenger
- 原理
原理是啥呢?从下面这个例子应该就很好理解了,grep hellcat-mes[s]*表示匹配所有包含了hellcat-mes 的字符串,[s]* 代表 0 或者多个 s 。由于用了 * ,所以能匹配到,然而上面使用的是 [s],表示需要包含 s 才能匹配到。
$ ps -ef|grep hellcat-mes[s]*
dev 1099472 1 2 11:44 ? 00:05:44 ./hellcat-messenger
dev 1276561 1248460 0 15:50 pts/23 00:00:00 grep --color=auto hellcat-mes[s]*
kill 通过进程名杀死进程的方法
结合 ps awk kill 杀死进程
ps -ef|grep hellcat-mes[s]|awk '{print $2}'|xargs kill -9
通过 pkill -9 删除 ,很可能杀不死
$ pkill -9 hellcat-messenger
$ ps -ef|grep hellcat-mes[s]
dev 1293134 1 3 16:01 ? 00:00:04 ./hellcat-messenger
并没有杀死,原因是啥呢?pkill其实是使用 pgrep 和 kill 来做到杀死进程的。
看看 pgrep 能不能匹配到此进程名?
$ pgrep hellcat-messenger
匹配不到,所以杀不掉这个进程。
但是通过
$ pgrep hellcat-mess
1293134
却可以查询到进程名,所以通过 pkill 就能杀死此进程
$ ps -ef|grep hellcat-mes[s]
dev 1293134 1 2 16:01 ? 00:00:08 ./hellcat-messenger
$ pkill hellcat-mess
$ ps -ef|grep hellcat-mes[s]
这应该算是 pgrep 的一个 bug 吧?有兴趣的可以看看 pgrep 的源代码看看原因。
转载请注明:MitNick » Linux grep 时不显示自身程序以及kill杀死进程的方法