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.
10 Answers 10
Just grep away grep itself!
process_id=`/bin/ps -fu $USER| grep "ABCD" | grep -v "grep" | awk '{print 2ドル}'`
3 Comments
$$ variablegrep a regular expression that matches the same thing, but appears different on the command line: ... | grep "[A]BCD" | awk ....Have you tried to use pidof ABCD ?
3 Comments
pgrep ABCDpidof command does not behave the same on every Linux distribution. So using pidof is not a good solution. It is also necessary to distinguish between the version of ps included in BusyBox - in lightweight Linux distributions (for example in a set-top box) and another ps, which is designed for full-fledged Linux. In the BusyBox version of the ps command, almost no arguments / switches work. In the case of BusyBox, the ps command is used a little differently. You have to be careful.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.
Comments
ps has an option for that:
process_id=`/bin/ps -C ABCD -o pid=`
Comments
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ドル}'
Comments
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
Comments
I found a better way to do this.
top -n 1 | grep "@#" | grep -Eo '^[^ ]+'
Comments
ps | pgrep ABCD
You can try the above command to return the process id of the ABCD process.
Comments
You can use 'pgrep #prog_name' instead and it shall return prog_name PID directly.
Comments
If you got below,
$ ps -ef | grep test
root 1322 1 0 10:31:17 ? 00:00:38 sh /test.sh
root 9078 8593 4 18:17:24 pts/1 00:00:00 grep switch
then, try this.
$ echo $(pgrep -f test.sh)
1332