Getting PID of process in Shell Script

2019-03-18 10:54发布

问题:

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:

Its 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 use this command to grep the pid of a particular process & echo $b to print pid of any running process

b=ps -ef | grep [f]irefox | awk '{ printf $2 }'

echo $b



回答6:

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}'