Getting PID of process in Shell Script

筅森魡賤 提交于 2019-12-20 10:31:10

问题


I am writing one shell script and I want to get PID of one process with name as "ABCD". What i did was :

process_id=`/bin/ps -fu $USER|grep "ABCD"|awk '{print $2}'`

This gets PID of two processes i.e. of process ABCD and the GREP command itself what if I don't want to get PID of GREP executed and I want PID only of ABCD process?

Please suggest.


回答1:


Just grep away grep itself!

process_id=`/bin/ps -fu $USER| grep "ABCD" | grep -v "grep" | awk '{print $2}'`



回答2:


Have you tried to use pidof ABCD ?




回答3:


It's very straight forward. ABCD should be replaced by your process name.

#!/bin/bash

processId=$(ps -ef | grep 'ABCD' | grep -v 'grep' | awk '{ printf $2 }')
echo $processId

Sometimes you need to replace ABCD by software name. Example - if you run a java program like java -jar TestJar.jar & then you need to replace ABCD by TestJar.jar.




回答4:


ps has an option for that:

process_id=`/bin/ps -C ABCD -o pid=`



回答5:


You can also do away with grep and use only awk.
Use awk's expression matching to match the process name but not itself.

/bin/ps -fu $USER | awk '/ABCD/ && !/awk/ {print $2}'



回答6:


You can use this command to grep the pid of a particular process & echo $b to print pid of any running process:

b=`ps -ef | grep [A]BCD | awk '{ printf $2 }'`
echo $b


来源:https://stackoverflow.com/questions/16965089/getting-pid-of-process-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!