Mayank Jain
Mayank Jain

Reputation: 2564

Getting PID of process in Shell Script

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.

Upvotes: 25

Views: 121953

Answers (10)

kevin
kevin

Reputation: 1

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

Upvotes: 0

Momen Mohamed
Momen Mohamed

Reputation: 1

You can use 'pgrep #prog_name' instead and it shall return prog_name PID directly.

Upvotes: 0

Varun Nair
Varun Nair

Reputation: 11

I found a better way to do this.

top -n 1 | grep "@#" | grep -Eo '^[^ ]+' 

Upvotes: 1

Leenu
Leenu

Reputation: 9

ps | pgrep ABCD

You can try the above command to return the process id of the ABCD process.

Upvotes: 0

A M S Rejuan
A M S Rejuan

Reputation: 466

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.

Upvotes: 9

Sandeep Singh
Sandeep Singh

Reputation: 11

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

Upvotes: 1

Gino Mempin
Gino Mempin

Reputation: 29660

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

Upvotes: 2

Salvador Fonseca
Salvador Fonseca

Reputation: 53

ps has an option for that:

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

Upvotes: 4

wizard
wizard

Reputation: 1554

Have you tried to use pidof ABCD ?

Upvotes: 38

blue
blue

Reputation: 2793

Just grep away grep itself!

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

Upvotes: 59

Related Questions