2017-04-14 63 views
0

我正在使用RHEL。我想通過命令如何在shell中grep tomcat Pid?

ps -ef | grep tomcat | awk '{print $2}' 

我的輸出是grep的Tomcat進程的PID,但我想只有28693

root  12854 0.0 0.0 112652 968 pts/0 S+ 01:12 0:00 grep --color=auto tomcat 
root  28693 2.1 45.0 7479444 1629972 ?  Sl Apr13 21:11 /usr/java/jdk1.8.0_45//bin/jav 

[[email protected] ~]# ps -ef | grep tomcat | awk '{print $2}' 
13240 
28693 

回答

0

使用pgrep

pgrep tomcat 

這將返回過程的唯一的PID。

隨着ps

ps -ef | grep tomcat | grep -v grep | awk '{print $2}' 
+0

謝謝。以及這也是爲我工作ps -ef | grep tomcat | awk'NR == 2 {print $ 2}' – uday

+0

如果輸出順序發生變化,該怎麼辦? – franklinsijo

0

ps -ef | grep to[m]cat | awk '{print $2}'

看到參數grep命令的一個字母前後的方括號?他們是一個正則表達式。正則表達式中的方括號表示「這些字母中的任何一個」。所以基本上,您正在尋找to,其次是方括號內的任何字母(僅在此爲m),然後爲cat。是的,這與字面上編寫tomcat的結果相同,但它確實防止grep找到它自己的命令行,因爲它不會找到字符串tomcat,而是to[m]cat。一個小技巧來防止grep匹配自己。